Skip to content

Backport (2.1): Fixes 38633: Reduce Redis cache memory via FQN-to-UUID indirection, compression, and memory guards - #38635

Open
harshach wants to merge 5 commits into
2.1from
backport/2.1/38633-redis-cache-memory-guards
Open

harshach wants to merge 5 commits into
2.1from
backport/2.1/38633-redis-cache-memory-guards

Conversation

@harshach

@harshach harshach commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Describe your changes:

Fixes #38633

Reduce Redis cache memory consumption and protect auth sessions under heavy ingestion workloads via five targeted changes:

  1. FQN-to-UUID indirection (:enid:): Store only the 36-char entity UUID under om:<ns>:enid:<type>:<fqnHash> instead of duplicating the full entity JSON under :en:. Name lookups resolve via two single-slot Redis commands (GET :enid: → HGET :e:<uuid> base), preserving cluster-mode hash-slot safety (ADR:2026-10-15-redis-commands-keep-their-keys-in-one-hash-slot). ID-based loads also populate :enid: when :e: succeeds; name invalidations evict :enid:, legacy :en:, and :rn: in one DEL for rolling-upgrade coherence; EntityLoaderWithName verifies FQN hash equality to reject stale aliases after renames.
  2. Transparent value compression (om:gz1:): Add CacheValueCodec (JDK built-in GZIP + Base64) for entity JSON and CachedReadBundle values at or above compressionThresholdBytes (default 0 on 2.1 patch releases for silent rolling upgrades/rollbacks; opt in via CACHE_COMPRESSION_THRESHOLD_BYTES=2048 once all pods are upgraded) when compression shrinks the UTF-8 byte length. Readers transparently decode both legacy plain JSON and compressed values, evicting corrupted entries on read.
  3. Configurable memory guards: Add excludedEntityTypes (YAML list or comma-separated env var, extending UNCACHED_ENTITY_TYPES and skipped by CacheWarmupApp), maxEntrySizeBytes (post-compression cap; 0 = unlimited; skipped entries do not write dangling :enid: pointers), wire unused tagTtlSeconds in CachedTagUsageDao (<= 0 disables tag caching), and downgrade per-write CachedEntityDao INFO logging to DEBUG.
  4. Skip Redis population on upsert lookup misses: Add EntityCacheBypass.skipPopulate() and wrap pre-write findByNameOrNull lookups in createOrUpdate, createOrUpdateForImport, and createOrUpdateBatchForImport when cache.populateOnUpsert is false (default). Warm entries still hit Redis and writes still evict stale keys across pods, while cold ingestion sweeps no longer fill Redis with unread entities.
  5. Session store isolation and bounded ZSET TTL: Add cache.sessionStore (auto|jdbc|redis) in SessionStoreFactory so operators can keep auth sessions in JDBC while using Redis maxmemory eviction policies, and bound RedisSessionStore per-user ZSET index TTLs monotonically via a single-key Lua script (ZADD + EXPIRE without shortening longer sessions).

Type of change:

  • Improvement

High-level design:

  • Architecture & ADR: Recorded in docs/decisions/2026-11-24-redis-cache-indirection-compression-and-memory-guards.md.
  • Key components changed:
    • CacheKeys, CachedEntityDao, EntityRepository (EntityLoaderWithName, EntityLoaderWithId), CacheWarmupApp: FQN→UUID :enid: indirection, write ordering (:e: before :enid:), FQN-match validation on name hit, and rolling-upgrade eviction of :enid: + :en: + :rn: in a single DEL.
    • CacheValueCodec + CachedEntityDao / CachedReadBundle / BundleWarmupBatcher / CacheWarmupApp: transparent GZIP+Base64 compression with om:gz1: prefix and post-compression maxEntrySizeBytes cap.
    • CacheConfig, conf/openmetadata.yaml, CachedTagUsageDao, CachedRelationshipDao, EntityCacheBypass: excludedEntityTypes, maxEntrySizeBytes, populateOnUpsert, sessionStore, tagTtlSeconds wiring, and EntityCacheBypass.skipPopulate().
    • SessionStoreFactory, RedisSessionStore: explicit jdbc / redis / auto session store mode and single-key Lua script ZADD_WITH_MAX_TTL_LUA for monotonic ZSET expiry.
  • Alternatives considered:
    • Multi-key Lua script for :enid: → :e: lookup: rejected because fqnHash and uuid hash to different Redis Cluster slots (CROSSSLOT, violates ADR:2026-10-15-redis-commands-keep-their-keys-in-one-hash-slot).
    • Reusing :en: with format sniffing: rejected because old pods during a rolling deploy would hit Jackson deserialization errors on UUID strings; :enid: keeps rolling deploys clean while deleting legacy :en: on invalidation.
  • Rollout / release notes:
    • Compression (CACHE_COMPRESSION_THRESHOLD_BYTES): Defaults to 0 (disabled) on 2.1 patch releases so rolling patch upgrades and rollbacks are silent; opt in with CACHE_COMPRESSION_THRESHOLD_BYTES=2048 once all pods run a version with om:gz1: decode support.
    • Reclaiming pre-existing :en: keys: Existing :en: full-JSON keys clear only on next entity write or TTL expiry (48h default). Once all pods are upgraded, operators needing immediate memory reclamation can safely run redis-cli --scan --pattern 'om:prod:en:*' | xargs -r -n 1000 redis-cli UNLINK (adjusting om:prod for custom keyspace).
    • Switching cache.sessionStore (CACHE_SESSION_STORE): Starts from an empty store; update all pods together and expect one forced sign-in for active users.
  • Counterpart PR: open-metadata/openmetadata-collate#8958

Tests:

Use cases covered

  • FQN-based entity lookups resolve through the 36-char :enid: UUID pointer to the single JSON copy in :e:, including after an ID-based DB load.
  • Wide table JSON and read bundles compress with om:gz1: and transparently round-trip on ID, FQN, single-bundle, and batch-bundle reads; corrupted entries are evicted on read.
  • Oversized entries past maxEntrySizeBytes are skipped without writing dangling :enid: pointers.
  • Entity types listed in cache.excludedEntityTypes (via CSV env var or YAML list) bypass Redis caching and CacheWarmupApp.
  • Upsert lookups under skipPopulate() hit warm Redis entries without writing cold misses back to Redis; concurrent write races evict both :e: and :enid:.
  • CachedTagUsageDao honors tagTtlSeconds and disables tag caching when tagTtlSeconds <= 0.
  • SessionStoreFactory honors cache.sessionStore=jdbc|redis|auto, and RedisSessionStore bounds per-user ZSET index TTLs monotonically on cluster-mode Redis 7.

Unit tests

  • I added unit tests for the new/changed logic.
  • Files added/updated:
    • openmetadata-service/src/test/java/org/openmetadata/service/cache/CacheValueCodecTest.java (4 tests)
    • openmetadata-service/src/test/java/org/openmetadata/service/cache/CacheConfigTest.java (4 tests)
    • openmetadata-service/src/test/java/org/openmetadata/service/cache/CachedEntityDaoIndirectionTest.java (10 tests)
    • openmetadata-service/src/test/java/org/openmetadata/service/cache/CachedEntityDaoAliasEvictionTest.java (5 tests)
    • openmetadata-service/src/test/java/org/openmetadata/service/cache/CachedMemoryGuardsTest.java (4 tests)
    • openmetadata-service/src/test/java/org/openmetadata/service/cache/BundleWarmupBatcherTest.java (10 tests)
    • openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/EntityLoaderIndirectionTest.java (6 tests)
    • openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/DeferredCacheInvalidationTest.java (7 tests)
    • openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/EntityCacheLoadRaceTest.java (3 tests)
    • openmetadata-service/src/test/java/org/openmetadata/service/security/session/SessionStoreFactoryTest.java (4 tests)
    • openmetadata-service/src/test/java/org/openmetadata/service/security/session/RedisSessionStoreTest.java (20 tests, cluster-mode Redis 7 via Testcontainers)
    • Plus regression runs: CacheBundleTest (4), CacheWarmupAppConfigParseTest (5), EntityCacheBypassTest (4), EntityRepositoryTagCacheTest (8) — 97/97 passed, 0 failures, 0 errors, 0 skipped.
  • Focused Java impact-map planner (python3 .github/scripts/plan_local_java_tests.py --scope focused): all 12 selected unit test classes ran and passed; .github/java-tests/impact-map.json branch check passed.

Backend integration tests

  • Not applicable for new REST endpoints (no backend REST API changes). Focused scope selected 0 local ITs; broader merge-queue ITs (--scope full / nightly scale & UI ITs) remain pending for merge readiness.

Focused unit verification passed on commit 48a23640cc4 (cherry-pick of #38634) (97/97 tests across all 12 impact-mapped unit classes + 3 additional cache/tag test classes, including cluster-mode Redis 7 RedisSessionStoreTest). Broader integration tests (--scope full) are pending merge queue / full verification.

Ingestion integration tests

  • Not applicable (no ingestion changes).

Playwright (UI) tests

  • Not applicable (no UI changes).

Not applicable (no UI changes).

Manual testing performed

  1. Verified cluster-mode Redis 7 behavior via RedisSessionStoreTest (Testcontainers redis:7-alpine --cluster-enabled yes) confirming ZADD_WITH_MAX_TTL_LUA preserves single-hash-slot execution and monotonic ZSET TTLs.
  2. Verified python3 scripts/harness/check_decision_records.py, python3 .github/scripts/plan_local_java_tests.py --check-branch, and pre-commit hooks (mvn spotless:apply / Java formatting).

UI screen recording:

Not applicable — backend Redis cache and configuration changes only; no UI changes.

Checklist:

  • I have read the CONTRIBUTING document.
  • My PR title is Fixes 38633: Reduce Redis cache memory via FQN-to-UUID indirection, compression, and memory guards
  • My PR is linked to a GitHub issue via Fixes #38633 above.
  • I have commented on my code, particularly in hard-to-understand areas.
  • For JSON Schema changes: Not applicable (no JSON Schema changes).
  • For a UI feature or feature task: Not applicable (backend-only change).
  • I have added tests (unit / integration / Playwright as applicable) and listed them above.
  • Self-review: I reviewed the final diff (48a23640cc4 (cherry-pick of #38634)) against REVIEW.md and confirmed no unresolved 🔴 findings (checked sibling upsert/import/bulk paths, cluster hash-slot compliance, rolling-upgrade eviction coherence, and concurrent write-epoch races).
  • Decision check: Added docs/decisions/2026-11-24-redis-cache-indirection-compression-and-memory-guards.md and verified with scripts/harness/check_decision_records.py.
  • I have added tests around the new logic.

…nd memory guards

- Store only the 36-char entity UUID under om:<ns>:enid:<type>:<fqnHash> and resolve FQN lookups via two single-slot commands (GET :enid: -> HGET :e:<uuid> base), populating the FQN pointer on ID loads too and evicting legacy :en: alongside :enid: and :rn: in one DEL.
- Add transparent GZIP+Base64 value compression (om:gz1:) via CacheValueCodec for entity JSON and read bundles above compressionThresholdBytes (default 2048).
- Add CacheConfig memory guards: excludedEntityTypes (YAML list or CSV env var), maxEntrySizeBytes, wire unused tagTtlSeconds in CachedTagUsageDao, and downgrade per-write CachedEntityDao INFO logging to DEBUG.
- Add EntityCacheBypass.skipPopulate() and use it on createOrUpdate* original lookups (default populateOnUpsert=false) so ingestion sweeps hit warm entries without writing cold misses to Redis.
- Add cache.sessionStore (auto|jdbc|redis) in SessionStoreFactory to isolate auth sessions in JDBC when desired, and bound RedisSessionStore per-user ZSET index TTLs monotonically via a single-key Lua script.
- Add ADR docs/decisions/2026-11-24-redis-cache-indirection-compression-and-memory-guards.md and unit tests.
@harshach
harshach requested a review from a team as a code owner November 24, 2026 23:27
@harshach
harshach requested review from yan-3005 and removed request for a team November 24, 2026 23:27
@github-actions

Copy link
Copy Markdown
Contributor

❌ PR checklist incomplete

This PR cannot be merged until the following are addressed on its linked issue:

  • No GitHub issue is linked. Link an issue in the Development section of the PR (or add Fixes #12345 to the description). For a same-org cross-repo issue, add Fixes open-metadata/<repo>#123 to the description.

The fields live on the linked issue in the Shipping project (open the issue → right sidebar → Projects). After you set them, re-run this check (or push a commit) — issue/project changes do not re-trigger it automatically.

Maintainers can bypass this check by adding the skip-pr-checks label.

Use CacheValueCodec.exceedsMaxEntrySize / encodedByteSize across
CachedEntityDao, CachedReadBundle, BundleWarmupBatcher, and
CacheWarmupApp so uncompressed non-ASCII values (e.g. CJK descriptions)
are checked against UTF-8 byte length rather than UTF-16 char count,
while compressed ASCII payloads continue using O(1) String.length().
…default, log level, exclusions, and ZSET TTL
@gitar-bot

gitar-bot Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Code Review ✅ Approved 🔴 High risk 1 closed / 1 findings

Changing Redis/JDBC session storage and index expiry affects authentication-session persistence; backend switches can invalidate active sessions and force users to sign in again.

Adds FQN-to-UUID indirection for Redis entity cache keys, GZIP+Base64 value compression, configurable memory guards (excludedEntityTypes, maxEntrySizeBytes, tagTtlSeconds), upsert cache bypass, and a cache.sessionStore option with monotonic ZSET TTLs. Resolved the finding where the Lua script shortened persistent pre-upgrade user index TTLs to a single session's duration. No open issues remain.

✅ 1 closed
✅ Security: Lua script shortens persistent pre-upgrade user index TTL to one session's

📄 openmetadata-service/src/main/java/org/openmetadata/service/security/session/RedisSessionStore.java:97-104 📄 openmetadata-service/src/main/java/org/openmetadata/service/security/session/RedisSessionStore.java:248-256
Before this change, per-user ZSET indexes had no TTL, so after an upgrade the live indexes have TTL == -1. The new script treats ttl < 0 as "needs a TTL" and runs EXPIRE KEYS[1] target, where target is the TTL of the session being written. Take a legacy index that holds session A (8h left) when the user logs in with a short session B (10 min). The whole index expires after 10 minutes, and A drops out of it while A's session key is still live.

SessionService.findRevocableSessions and applySessionLimit read sessions through findByUserIdAndStatus. Once the index is gone, deleting or revoking that user can leave A usable, and the per-user session limit stops counting it. Because the script reads TTL after ZADD, it cannot tell a newly created key (also -1) from a legacy persistent one.

Fix: read TTL before the ZADD. Apply EXPIRE only when the key did not exist (-2) or when its existing finite TTL is shorter than target. Leave legacy persistent indexes alone, or give them a conservative maximum session lifetime instead.

Verification

Rules No rules evaluated

Functional validation Not enabled

Set up

Auto-approval Not enabled

Set up

For more verification details, comment gitar display:verbose.

Options

Display: compact → Showing compact verification results.

Comment with these commands to change the behavior for this request:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant