Repository navigation
Fixes 38633: Reduce Redis cache memory via FQN-to-UUID indirection, compression, and memory guards - #38634
Fixes 38633: Reduce Redis cache memory via FQN-to-UUID indirection, compression, and memory guards#38634harshach wants to merge 6 commits into
Conversation
482e583 to
dc32252
Compare
…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.
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().
1d37140 to
f008bf9
Compare
manerow
left a comment
There was a problem hiding this comment.
I reviewed this at f008bf9e9c7 and ran it locally on the Redis lane profile (Postgres, Elasticsearch, Redis). The run combined a scenario test of my own with the existing cache/*IT, RedisSessionStoreIT and GlossaryTermResourceIT: 390 test cases, 0 failures, 20 skipped. The scenarios check that:
- A name lookup stores only the id pointer. A wide entity is stored once and compressed (9.6 KB down to 1.2 KB on a test chart with very repetitive text), with no
:en:copy. A load by id writes the pointer too. - A rename deletes the old pointer, and the old name returns not found. A stale pointer, like one an older pod leaves behind, fails the FQN check and is deleted.
- A legacy
:en:copy is ignored on read and dropped on the next write. A plain value written by an older pod is still read. A corrupted compressed value is replaced from the database. maxEntrySizeBytesandexcludedEntityTypesskip the write without leaving a pointer behind.- An unchanged upsert does not fill Redis by default. With
populateOnUpsert: trueit does.
I found no blocking issue in the code. I also read the race handling, where the id loader now deletes the name keys as well, and it looks right; I haven't tested it beyond your unit tests. The comments below are about rollout and docs.
…sions, and ZSET TTL
TeddyCr
left a comment
There was a problem hiding this comment.
Reviewed at PR head f008bf9e9c7 (and cross-checked against 8be7d435edb on refs/heads/agent/we-are-using-redis-for-cachi, which has not synchronized onto refs/pull/38634/head or run CI yet).
Requesting changes for four functional issues detailed inline:
- REST
PUTupserts and unchanged updates still populate Redis whenpopulateOnUpsert=false(EntityResource.createOrUpdateresolvesResourceContextwithfromCache=truebeforerepository.createOrUpdate, andupdate*field hydration +GlossaryTermRepository.createOrUpdateForImportrun outsideskipPopulateOnUpsert()). ContainerRepository.hydrateRefsByFqnbypassesisCacheableEntityType(CONTAINER)whiledeferOrInvalidateRedisL2skips eviction for excluded types, leaving deleted/staleom:<ns>:rn:container:*entries cached for 48h whencontaineris inexcludedEntityTypes(plus8be7d435edbneeds to sync onto the PR head).tagTtlSecondsis bypassed byCachedReadBundle/BundleWarmupBatcher, which still cachedto.tagsforentityTtlSeconds(48h) whentagTtlSeconds <= 0and re-populate expiredCachedTagUsageDaokeys with stale bundle tags when0 < tagTtlSeconds < entityTtlSeconds.RedisSessionStoreZADD_WITH_MAX_TTL_LUAvs pre-upgradeTTL == -1user indexes: onf008bf9e9c7,ttl < 0shrinks persistent pre-upgrade indexes to a short session's TTL (breakingapplySessionLimitandrevokeAllUserSessionson user off-boarding); in8be7d435edb, skippingprior == -1leaves every pre-upgrade user's ZSET permanently without a TTL becausecreateActiveSessionZADDs the new session beforeapplySessionLimitZREMs expired ones.
…tagTtlSeconds, and legacy session ZSET TTLs
Code Review ✅ Approved 🔴 High risk 2 closed / 2 findingsChanging session-store selection and Redis session-index expiry affects authentication state; switching backends could invalidate active sessions and force sign-in. Reduces Redis cache memory via FQN-to-UUID ✅ 2 closed✅ Edge Case: maxEntrySizeBytes compares UTF-16 char count, not bytes
✅ Edge Case: encode() still compares UTF-16 chars, so non-ASCII values skip compression
VerificationRules No rules evaluated Functional validation Not enabledAuto-approval Not enabledFor more verification details, comment OptionsDisplay: compact → Showing compact verification results. Comment with these commands to change the behavior for this request:
Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source |
Describe your changes:
Fixes #38633
Reduce Redis cache memory consumption and protect auth sessions under heavy ingestion workloads via five targeted changes:
:enid:): Store only the 36-char entity UUID underom:<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 oneDELfor rolling-upgrade coherence;EntityLoaderWithNameverifies FQN hash equality to reject stale aliases after renames.om:gz1:): AddCacheValueCodec(JDK built-in GZIP + Base64) for entity JSON andCachedReadBundlevalues at or abovecompressionThresholdBytes(default2048;0disables) when compression shrinks the value. Readers transparently decode both legacy plain JSON and compressed values, evicting corrupted entries on read.excludedEntityTypes(YAML list or comma-separated env var, extendingUNCACHED_ENTITY_TYPESand skipped byCacheWarmupApp),maxEntrySizeBytes(post-compression cap;0= unlimited; skipped entries do not write dangling:enid:pointers), wire unusedtagTtlSecondsinCachedTagUsageDao(<= 0disables tag caching), and downgrade per-writeCachedEntityDaoINFOlogging toDEBUG.EntityCacheBypass.skipPopulate()and wrap pre-writefindByNameOrNulllookups increateOrUpdate,createOrUpdateForImport, andcreateOrUpdateBatchForImportwhencache.populateOnUpsertisfalse(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.cache.sessionStore(auto|jdbc|redis) inSessionStoreFactoryso operators can keep auth sessions in JDBC while using Redismaxmemoryeviction policies, and boundRedisSessionStoreper-user ZSET index TTLs monotonically via a single-key Lua script (ZADD+EXPIREwithout shortening longer sessions).Type of change:
High-level design:
docs/decisions/2026-11-24-redis-cache-indirection-compression-and-memory-guards.md.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 singleDEL.CacheValueCodec+CachedEntityDao/CachedReadBundle/BundleWarmupBatcher/CacheWarmupApp: transparent GZIP+Base64 compression withom:gz1:prefix and post-compressionmaxEntrySizeBytescap.CacheConfig,conf/openmetadata.yaml,CachedTagUsageDao,CachedRelationshipDao,EntityCacheBypass:excludedEntityTypes,maxEntrySizeBytes,populateOnUpsert,sessionStore,tagTtlSecondswiring, andEntityCacheBypass.skipPopulate().SessionStoreFactory,RedisSessionStore: explicitjdbc/redis/autosession store mode and single-key Lua scriptZADD_WITH_MAX_TTL_LUAfor monotonic ZSET expiry.:enid:→:e:lookup: rejected becausefqnHashanduuidhash to different Redis Cluster slots (CROSSSLOT, violatesADR:2026-10-15-redis-commands-keep-their-keys-in-one-hash-slot).: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.CACHE_COMPRESSION_THRESHOLD_BYTES): Defaults to2048onmain(and0opt-in on2.1/2.0patch backports for zero-noise rolling patch upgrades and rollback safety). During rolling upgrades onmainfrom pods withoutom:gz1:decode support, operators who want zero log/DB noise can temporarily setCACHE_COMPRESSION_THRESHOLD_BYTES=0until all pods are upgraded.:en:keys: Upgrading does not proactively delete existing:en:full-JSON entries — they clear only on next entity write or entity TTL expiry (48h in shippedopenmetadata.yaml). To reclaim memory immediately once all pods run this version (nothing reads:en:anymore), scan<keyspace>:en:*(defaultom:prod:en:*) and delete with non-blockingUNLINK:redis-cli --scan --pattern 'om:prod:en:*' | xargs -r -n 1000 redis-cli UNLINK.cache.sessionStore(CACHE_SESSION_STORE): ChangingsessionStore(e.g.auto→jdbc) switches to an empty session store (JwtFilterrejects missing sessions with"Invalid session"). Switch all pods together (do not run mixed values across pods) and expect one forced sign-in for active users.Tests:
Use cases covered
:enid:UUID pointer to the single JSON copy in:e:, including after an ID-based DB load.om:gz1:and transparently round-trip on ID, FQN, single-bundle, and batch-bundle reads; corrupted entries are evicted on read.maxEntrySizeBytesare skipped without writing dangling:enid:pointers.cache.excludedEntityTypes(via CSV env var or YAML list) bypass Redis caching andCacheWarmupApp.skipPopulate()hit warm Redis entries without writing cold misses back to Redis; concurrent write races evict both:e:and:enid:.CachedTagUsageDaohonorstagTtlSecondsand disables tag caching whentagTtlSeconds <= 0.SessionStoreFactoryhonorscache.sessionStore=jdbc|redis|auto, andRedisSessionStorebounds per-user ZSET index TTLs monotonically on cluster-mode Redis 7.Unit tests
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)CacheBundleTest(4),CacheWarmupAppConfigParseTest(5),EntityCacheBypassTest(4),EntityRepositoryTagCacheTest(8) — 97/97 passed, 0 failures, 0 errors, 0 skipped.python3 .github/scripts/plan_local_java_tests.py --scope focused): all 12 selected unit test classes ran and passed;.github/java-tests/impact-map.jsonbranch check passed.Backend integration tests
--scope full/ nightly scale & UI ITs) remain pending for merge readiness.Focused unit verification passed on commit
9b399b40ae6(97/97 tests across all 12 impact-mapped unit classes + 3 additional cache/tag test classes, including cluster-mode Redis 7RedisSessionStoreTest). Broader integration tests (--scope full) are pending merge queue / full verification.Ingestion integration tests
Playwright (UI) tests
Not applicable (no UI changes).
Manual testing performed
RedisSessionStoreTest(Testcontainersredis:7-alpine --cluster-enabled yes) confirmingZADD_WITH_MAX_TTL_LUApreserves single-hash-slot execution and monotonic ZSET TTLs.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:
Fixes 38633: Reduce Redis cache memory via FQN-to-UUID indirection, compression, and memory guardsFixes #38633above.9b399b40ae6) againstREVIEW.mdand confirmed no unresolved 🔴 findings (checked sibling upsert/import/bulk paths, cluster hash-slot compliance, rolling-upgrade eviction coherence, and concurrent write-epoch races).docs/decisions/2026-11-24-redis-cache-indirection-compression-and-memory-guards.mdand verified withscripts/harness/check_decision_records.py.