Skip to content

Fixes 38633: Reduce Redis cache memory via FQN-to-UUID indirection, compression, and memory guards - #38634

Open
harshach wants to merge 6 commits into
mainfrom
agent/we-are-using-redis-for-cachi
Open

harshach wants to merge 6 commits into
mainfrom
agent/we-are-using-redis-for-cachi

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 2048; 0 disables) when compression shrinks the value. 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 2048 on main (and 0 opt-in on 2.1 / 2.0 patch backports for zero-noise rolling patch upgrades and rollback safety). During rolling upgrades on main from pods without om:gz1: decode support, operators who want zero log/DB noise can temporarily set CACHE_COMPRESSION_THRESHOLD_BYTES=0 until all pods are upgraded.
    • Reclaiming pre-existing :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 shipped openmetadata.yaml). To reclaim memory immediately once all pods run this version (nothing reads :en: anymore), scan <keyspace>:en:* (default om:prod:en:*) and delete with non-blocking UNLINK:
      redis-cli --scan --pattern 'om:prod:en:*' | xargs -r -n 1000 redis-cli UNLINK.
    • Switching cache.sessionStore (CACHE_SESSION_STORE): Changing sessionStore (e.g. auto → jdbc) switches to an empty session store (JwtFilter rejects 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.
  • Counterpart PR: open-metadata/openmetadata-collate#8957

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 9b399b40ae6 (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 (9b399b40ae6) 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.

@harshach
harshach requested a review from a team as a code owner November 24, 2026 23:27
@harshach
harshach requested review from TeddyCr and a balanced review from Copilot November 24, 2026 23:27

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

Copilot AI balanced review requested due to automatic review settings November 24, 2026 23:39

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@harshach
harshach force-pushed the agent/we-are-using-redis-for-cachi branch from 482e583 to dc32252 Compare November 25, 2026 00:51
Copilot AI balanced review requested due to automatic review settings November 25, 2026 00:51

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

Copilot AI balanced review requested due to automatic review settings November 25, 2026 02:51

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

…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().
@harshach
harshach force-pushed the agent/we-are-using-redis-for-cachi branch from 1d37140 to f008bf9 Compare November 25, 2026 03:02
Copilot AI balanced review requested due to automatic review settings November 25, 2026 03:02

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@manerow manerow left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
  • maxEntrySizeBytes and excludedEntityTypes skip the write without leaving a pointer behind.
  • An unchanged upsert does not fill Redis by default. With populateOnUpsert: true it 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.

Comment thread conf/openmetadata.yaml Resolved
Comment thread conf/openmetadata.yaml Resolved

@TeddyCr TeddyCr left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. REST PUT upserts and unchanged updates still populate Redis when populateOnUpsert=false (EntityResource.createOrUpdate resolves ResourceContext with fromCache=true before repository.createOrUpdate, and update* field hydration + GlossaryTermRepository.createOrUpdateForImport run outside skipPopulateOnUpsert()).
  2. ContainerRepository.hydrateRefsByFqn bypasses isCacheableEntityType(CONTAINER) while deferOrInvalidateRedisL2 skips eviction for excluded types, leaving deleted/stale om:<ns>:rn:container:* entries cached for 48h when container is in excludedEntityTypes (plus 8be7d435edb needs to sync onto the PR head).
  3. tagTtlSeconds is bypassed by CachedReadBundle / BundleWarmupBatcher, which still cache dto.tags for entityTtlSeconds (48h) when tagTtlSeconds <= 0 and re-populate expired CachedTagUsageDao keys with stale bundle tags when 0 < tagTtlSeconds < entityTtlSeconds.
  4. RedisSessionStore ZADD_WITH_MAX_TTL_LUA vs pre-upgrade TTL == -1 user indexes: on f008bf9e9c7, ttl < 0 shrinks persistent pre-upgrade indexes to a short session's TTL (breaking applySessionLimit and revokeAllUserSessions on user off-boarding); in 8be7d435edb, skipping prior == -1 leaves every pre-upgrade user's ZSET permanently without a TTL because createActiveSession ZADDs the new session before applySessionLimit ZREMs expired ones.

@harshach

Copy link
Copy Markdown
Collaborator Author

@manerow @TeddyCr All review comments have been addressed and propagated across all three branches (main b1fa06938cc on #38634, 2.1 3eac67f1680 on #38635, and 2.0 7514adbae30 on #38636, plus synced openmetadata-collate config PRs #8957 / #8958 / #8959). PTAL!

Copilot AI balanced review requested due to automatic review settings November 28, 2026 04:24

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@gitar-bot

gitar-bot Bot commented Nov 28, 2026

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

Changing 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 :enid: indirection, GZIP+Base64 compression with om:gz1: prefix, configurable memory guards (excludedEntityTypes, maxEntrySizeBytes, tagTtlSeconds), upsert lookup population skipping, and session store isolation with bounded ZSET TTLs. Resolved the earlier finding where maxEntrySizeBytes and CacheValueCodec.encode() compared UTF-16 char counts instead of UTF-8 bytes, so size guards and compression now behave correctly for non-ASCII values. No open issues remain.

✅ 2 closed
✅ Edge Case: maxEntrySizeBytes compares UTF-16 char count, not bytes

📄 openmetadata-service/src/main/java/org/openmetadata/service/cache/CachedEntityDao.java:293-295 📄 openmetadata-service/src/main/java/org/openmetadata/service/cache/CachedReadBundle.java:143-144 📄 openmetadata-service/src/main/java/org/openmetadata/service/cache/BundleWarmupBatcher.java:191-193 📄 openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/cache/CacheWarmupApp.java:508-510
The size guard compares encoded.length(), which counts UTF-16 chars, against maxEntrySizeBytes. The config comment, yaml and ADR all describe that limit as a post-compression byte size. A Base64 output is ASCII, so the two counts agree once a value is compressed. They diverge when compression is off (compressionThresholdBytes=0, which the ADR recommends during rolling upgrades) or when gzip does not shrink the value. In those cases, plain JSON with non-ASCII text such as CJK descriptions can take up to 3× the cap in Redis and still pass the guard. Fix: measure encoded.getBytes(StandardCharsets.UTF_8).length in one shared helper, or skip the conversion when the value is compressed and so known to be ASCII. Use that helper in CachedEntityDao, CachedReadBundle, BundleWarmupBatcher and CacheWarmupApp.

✅ Edge Case: encode() still compares UTF-16 chars, so non-ASCII values skip compression

📄 openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheValueCodec.java:34 📄 openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheValueCodec.java:42 📄 openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheValueCodec.java:61-75
This commit changes the size guard to count UTF-8 bytes, but encode still decides whether to compress by comparing encoded.length() < raw.length(), and that is a UTF-16 char count. Take a CJK-heavy entity of 1,000 chars, which is 3,000 UTF-8 bytes. If its Base64 gzip output is 1,200 chars, encode keeps the raw value because 1,200 is not less than 1,000. Redis then stores 3,000 bytes instead of about 1,200, and the new byte-accurate exceedsMaxEntrySize can drop the entry when the compressed form would have fit under the limit. The fix is to compare the compressed length with rawBytes.length. Base64 output is ASCII, so its char count already equals its byte count.

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.

Reduce Redis cache memory usage via FQN-to-UUID indirection, value compression, and memory guards

4 participants