You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@gravitino.apache.org by "yuqi1129 (via GitHub)" <gi...@apache.org> on 2026/06/18 14:17:43 UTC
[PR] [#11737] docs(core): add multi-node entity store cache invalidation design [gravitino]
yuqi1129 opened a new pull request, #11738:
URL: https://github.com/apache/gravitino/pull/11738
### What changes were proposed in this pull request?
Adds a design doc, `design-docs/entity-cache-multinode-changelog-design.md`, proposing how to make the entity store cache (`gravitino.cache.enabled`) usable in multi-node deployments by invalidating it across nodes via the existing `entity_change_log` and `EntityChangeLogPoller`. It presents two options (coarse by-metalake vs. precise per-endpoint) with a recommendation, plus a consistency model and a coverage audit.
### Why are the changes needed?
Today the entity store cache only invalidates locally, so multi-node deployments must disable it, which hurts performance (Iceberg especially). This is design-only; no code behavior changes yet.
Fix: #11737
### Does this PR introduce _any_ user-facing change?
No. Documentation and design only.
### How was this patch tested?
No code changes; not applicable. The doc passes the repo docs-style audit scripts.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3543807983
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -0,0 +1,350 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+---
+title: "Multi-Node Support for the Entity Store Cache"
+status: "Draft"
+date: "2026-07-07"
+---
+
+## Background
+
+Gravitino has two caches:
+
+- The **jcasbin authorization cache** already works with more than one node.
+- The **entity store cache** does not. When a change happens on node A, only node A clears its cache. Node B keeps serving the old data until its entry expires.
+
+Because of this, the only safe way to run more than one node today is to turn the entity store cache off (`gravitino.cache.enabled=false`). That is bad for read-heavy catalogs, especially Iceberg.
+
+This document proposes a design to make the entity store cache correct when running more than one node. It is a design proposal; no behavior has changed yet.
+
+## Goals and Non-Goals
+
+**Goals**
+
+- Make the entity store cache correct with more than one node, so `gravitino.cache.enabled=true` is safe.
+- Keep the cache **pluggable**: one SPI, chosen by `gravitino.cache.impl`. Ship `caffeine` as the default (no extra dependency) and `redis` as an option the user turns on by config.
+- Keep single-node behavior and the write path (the optimistic version lock) unchanged.
+
+**Non-Goals**
+
+- Replace the entity store or its write path. The cache sits in front of the store and is never the source of truth.
+- Add a cluster membership / gossip layer or any other complex distributed system. We only use the DB Gravitino already needs, or the external cache the user turns on.
+
+---
+
+## Current Cache Implementation
+
+`EntityCache` is already an SPI, chosen by `gravitino.cache.impl` and created by `CacheFactory`. There is one implementation today, `CaffeineEntityCache` (`caffeine`): an in-memory cache, **one copy per node**, with two kinds of entries:
+
+- **entity keys** `(ident, type)` → the entity itself;
+- **relation keys** `(ident, type, relType)` → the list of related entities, stored **in both directions** and kept in step by an in-process **reverse index** (`ReverseIndexCache`).
+
+On a write, the node clears the changed key and then uses the reverse index to clear the related keys. On a single node this is correct. The problem is that this clearing happens **only on the node that made the change** (`RelationalEntityStore` calls `cache.invalidate(...)` locally). Nothing tells the other nodes, so they serve old data until their entries expire.
+
+Some behavior is already safe with more than one node and does not change:
+
+| Already correct | Why |
+| ------------------------- | ---------------------------------------------------------------------------- |
+| Writes never lose updates | The write path reads the DB (not the cache) with an optimistic version check |
+| `list(namespace)` | Skips the cache, so it is never stale |
+| CREATE | Needs nothing: no negative caching, and `list` skips the cache |
+
+The rest of the problem splits in two:
+
+- **entity keys** are one-to-one. "table T changed" names exactly the key to drop, and any node can drop it. This is easy.
+- **relation keys** have a reverse key. Dropping one side (say a role) also means dropping the other side's key (each user that had the role), but "the role changed" does not say *which* users those are. The writing node knows them from its local reverse index; a remote node may not.
+
+That reverse key is the hard part. So the first question is whether the cache needs relations at all.
+
+---
+
+## Do We Need to Cache Relations?
+
+All the cross-node difficulty comes from relation caching (the reverse key and the write fan-out). Before building around it, we checked whether it is actually important for performance. It is not.
+
+**Who reads the relation cache.** The cached relation path is `RelationalEntityStore.listEntitiesByRelation`, which runs **one indexed SQL join** per call (`JDBCBackend.listEntitiesByRelation`). Its callers are all metadata governance managers:
+
+| Caller | Relation | API that uses it |
+| -------------------- | ---------------------------- |-----------------------------------|
+| `OwnerManager` | `OWNER_REL` | `GET .../owner` |
+| `RoleManager` | role relations | role / authorization management |
+| `FutureGrantManager` | role/user/group relations | applying future grants (admin op) |
+| `TagManager` | `TAG_METADATA_OBJECT_REL` | tag endpoints |
+| `PolicyManager` | `POLICY_METADATA_OBJECT_REL` | policy endpoints |
+
+**Who does not.** The two paths that must be fast do **not** use it:
+
+- **Core metadata reads** (`get` / `list` of table, schema, catalog, …) never call `listEntitiesByRelation`. Removing the relation cache does not affect them at all.
+- **Authorization checks** (`JcasbinAuthorizer`) read roles straight from mappers (`RoleMetaMapper.listRolesByUserId` / `listRolesByGroupId`), owner from its own `ownerRelCache` (which polls `owner_meta`), and id from its own `metadataIdCache`. It does not use the entity store relation cache at all. Relation caching was first added with authorization in mind, but authorization no longer uses it.
+
+**Cost of removing it.** Each call becomes one indexed query — not an N+1 (one query per item). No list endpoint loads relations per item in a loop. The one place a single request makes several queries is **tag / policy inheritance**: listing an object's tags also reads its parents (the object plus up to ~3 ancestors), so a tag lookup is up to ~4 single-row queries; the cache mainly saves re-reading popular parents. This is the only workload where removing the cache adds real DB load, and it can be measured today — those calls are already `@Monitored` (`baseMetricName = "listTagsForMetadataObject"`, `"getOwner"`, `"listPoliciesForMetadataObject"`).
Review Comment:
Is it possible to reduce to 1 query for tag operation?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3584989037
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -252,54 +254,68 @@ The entity store cache becomes a third consumer of the poller, next to the catal
### Consistency
-The cache is never the source of truth. The write path always reads the DB under the optimistic version lock, so eventual consistency can **never** cause a lost update or corrupt data. Its only observable effect is **bounded read staleness on non-writing nodes**: for up to one poll interval, a node other than the writer may serve an older value.
+The cache never holds the truth. Every write goes to the DB first, under the version lock, so a stale cache can **never** cause a lost update or a bad write. The only thing that can go wrong is that a read on **another node** returns an old value for a short time — at most one poll interval, until that node drops the key.
-- **Other nodes:** eventual — an entity key is dropped within one poll interval of the change.
-- **Writing node:** unchanged — it still clears its own cache on the write path, so it reads its own writes right away. Its own row is replayed later, which does nothing (clearing an already-clear key is a no-op).
-- **Write path:** unchanged — it reads the DB with the optimistic version check.
+So the real question is simple: when another node reads an old value, does it matter? We went through every alter and every drop, for every cached entity, one at a time. A stale read falls into one of two buckets:
-The rest of this section works through every way that staleness window can be observed, and how each is handled.
+- **The old value makes the next step fail with an error.** The user sees the error and tries again. This is safe.
+- **The old value is used silently and gives a wrong answer, with no error.** This is the dangerous kind.
-#### Staleness scenarios and mitigations
+We only need to worry about the second bucket.
-**1. Plain stale read (bounded, mostly tolerable).**
+#### Two groups of cached entities
-| # | Scenario | Effect | Possible mitigation |
-| - | -------------------------------------------------------------- |-----------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------|
-| 1 | Node A ALTERs a table (add column); B GETs it | B serves the old schema for up to one poll interval | Accept within the SLA window; a caller that needs an exact schema uses a consistent (cache-bypass) read |
-| 2 | Node A DROPs a table; B GETs it | B still reports it as present (cache hit) until the next poll | Accept — any write to it on B is re-validated against the DB and rejected as not-found, so no corruption |
-| 3 | RENAME (the old name behaves like a DROP); B GETs the old name | B keeps resolving the old name until the next poll; the new name misses → DB load | Same as DROP — bounded by the poll interval |
-| 4 | A property changes (e.g. Iceberg metadata-location); B GETs it | B returns the old location → a query on B may read an old snapshot/path | Highest-value case: offer a consistent (cache-bypass) read for location-sensitive callers, or use `redis` |
+The danger depends on where the real data comes from.
-**2. Read-your-writes across nodes.**
+**Group 1 — the data comes from the connector: table, view, topic, and schemas in external catalogs.** For these, Gravitino does not read the metadata from its own cache. On every load it asks the underlying system (Hive, Iceberg, JDBC, Kafka) for the current object, and uses the cached entity only for Gravitino's own id and audit fields. All nodes ask the same underlying system, so they all see the same thing. If the object was dropped or renamed, the connector call fails right away with a "not found" error. **This whole group is safe — nothing to do.**
-| # | Scenario | Effect | Possible mitigation |
-| - |---------------------------------------------------------------------|-------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
-| 5 | Through a load balancer, ALTER on A then an immediate read on B | Stale — violates session consistency; without sticky routing the change looks lost | Sticky sessions at the LB, or a client-supplied last-seen version that bypasses the cache when the copy is older; `redis` removes it entirely |
-| 6 | CREATE (rather than ALTER/DROP) | No problem — no negative caching and `list` skips the cache, so a new entity is visible at once | None needed |
+**Group 2 — the data comes from Gravitino's own store: metalake, catalog, managed schema, fileset, model, model version, function.** Here the cached entity *is* the answer, so a stale read really can return an old value. We looked at each alter in this group.
-**3. Cross-node read-modify-write.**
+(Views follow the same rule as tables: their definition is read through the connector on every load, so they sit in Group 1 and are safe.)
-| # | Scenario | Effect | Possible mitigation |
-| - | ------------------------------------------------------------------------------------- |-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------|
-| 7 | B reads stale value A and submits an update carrying A's version as the expected one | The optimistic lock rejects it on version mismatch — safe, but the user sees an unexpected conflict | Accept (correctness is preserved); reduce its frequency with the read-your-writes mitigations above |
+#### Walking through the alters in Group 2
-**4. Is the window actually bounded? — poller reliability (the real risk).** The "at most one poll interval" guarantee holds **only if the poller never drops a row**. If it does, the stale entry survives until the cache TTL, so this is the one place eventual consistency itself can break.
+Most alters are safe:
-| # | Scenario | Effect | Possible mitigation |
-| -- |-----------------------------------------------------------------------------------------------------------|-----------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------|
-| 8 | Commit-ordering gap / a skipped row | The key is never invalidated; stale until the TTL | Reuse the lag-safe, id-based polling already built for the change log (`#11736`); keep the cache TTL as a backstop |
-| 9 | Poller thread dies / DB briefly unreachable | That node serves stale data until the TTL | TTL backstop + monitor poller liveness/lag and alert |
-| 10 | Hierarchical DROP: only the container (schema) emits a row; children are cleared by a forward prefix scan | Correct as long as the prefix scan covers every child key | Cover with the hierarchical-drop test; confirm no child is written in a separate transaction that outlives the container row |
+| Change | What a stale read does | Safe? |
+| -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
+| rename (metalake, catalog, schema, fileset, model) | reading the old name returns a leftover copy, but any write to it goes to the DB and fails; the new name misses the cache and loads fresh from the DB | yes |
+| update comment | you see an old comment for a moment | yes |
+| set / remove property (metalake, model, fileset) | these properties do not change where the data lives | yes |
+| fileset storage location | **cannot be changed** — there is no alter for it, so it can never go stale | yes |
+| drop | for Group 1 the connector call fails; for a fileset the file path is gone and access fails | yes |
+| catalog changes | already handled today by a separate cross-node signal (`CatalogChangeLogListener`), not by this cache | yes |
-**5. Idempotency (no issue).** Replaying ALTER then DROP, in any order or duplicated, is safe: invalidation is idempotent, so out-of-order or repeated replay has no effect.
+Five cases are **not** safe — a stale read gives a wrong answer with no error. They are in the model area, functions, or the metalake on/off flag:
-#### Summary: main risks, resolutions, and the staleness SLA
+| Change | Why a stale read is wrong, with no error |
+| --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| model version — update / add / remove URI | the URI points to the model files. An old URI silently loads the **wrong model files**. |
+| model version — update aliases | an alias silently points to the **wrong version**. |
+| model — latest version (after a new version is added on another node) | "get the latest version" silently returns an **old version**. |
+| function — add / update / remove implementation or definition | the implementation is the code the function runs. An old copy silently runs the **wrong function code**. |
+| metalake — disable | a node with a stale copy still thinks the metalake is on and **lets operations run** on a metalake that was turned off. (Turning it back on is safe: a stale node only throws "in use" by mistake.) |
Review Comment:
Yes, that's what I concerned about. We can start without tag. But we need to think about it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3540949943
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -0,0 +1,349 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+---
+title: "Multi-Node Support for the Entity Store Cache"
+status: "Draft"
+date: "2026-07-07"
+---
+
+## Background
+
+Gravitino has two caches:
+
+- The **jcasbin authorization cache** already works with more than one node.
+- The **entity store cache** does not. When a change happens on node A, only node A clears its cache. Node B keeps serving the old data until its entry expires.
+
+Because of this, the only safe way to run more than one node today is to turn the entity store cache off (`gravitino.cache.enabled=false`). That is bad for read-heavy catalogs, especially Iceberg.
+
+This document makes the entity store cache correct when running more than one node.
+
+## Goals and Non-Goals
+
+**Goals**
+
+- Make the entity store cache correct with more than one node, so `gravitino.cache.enabled=true` is safe.
+- Keep the cache **pluggable**: one SPI, chosen by `gravitino.cache.impl`. Ship `caffeine` as the default (no extra dependency) and `redis` as an option the user turns on by config.
+- Keep single-node behavior and the write path (the optimistic version lock) unchanged.
+
+**Non-Goals**
+
+- Replace the entity store or its write path. The cache sits in front of the store and is never the source of truth.
+- Add a cluster membership / gossip layer or any other complex distributed system. We only use the DB Gravitino already needs, or the external cache the user turns on.
+
+---
+
+## Current Cache Implementation
+
+`EntityCache` is already an SPI, chosen by `gravitino.cache.impl` and created by `CacheFactory`. There is one implementation today, `CaffeineEntityCache` (`caffeine`): an in-memory cache, **one copy per node**, with two kinds of entries:
+
+- **entity keys** `(ident, type)` → the entity itself;
+- **relation keys** `(ident, type, relType)` → the list of related entities, stored **in both directions** and kept in step by an in-process **reverse index** (`ReverseIndexCache`).
+
+On a write, the node clears the changed key and then uses the reverse index to clear the related keys. On a single node this is correct. The problem is that this clearing happens **only on the node that made the change** (`RelationalEntityStore` calls `cache.invalidate(...)` locally). Nothing tells the other nodes, so they serve old data until their entries expire.
+
+Some behavior is already safe with more than one node and does not change:
+
+| Already correct | Why |
+| ------------------------- | ---------------------------------------------------------------------------- |
+| Writes never lose updates | The write path reads the DB (not the cache) with an optimistic version check |
+| `list(namespace)` | Skips the cache, so it is never stale |
+| CREATE | Needs nothing: no negative caching, and `list` skips the cache |
+
+The rest of the problem splits in two:
+
+- **entity keys** are one-to-one. "table T changed" names exactly the key to drop, and any node can drop it. This is easy.
+- **relation keys** have a reverse key. Dropping one side (say a role) also means dropping the other side's key (each user that had the role), but "the role changed" does not say *which* users those are. The writing node knows them from its local reverse index; a remote node may not.
+
+That reverse key is the hard part. So the first question is whether the cache needs relations at all.
+
+---
+
+## Do We Need to Cache Relations?
+
+All the cross-node difficulty comes from relation caching (the reverse key and the write fan-out). Before building around it, we checked whether it is actually important for performance. It is not.
+
+**Who reads the relation cache.** The cached relation path is `RelationalEntityStore.listEntitiesByRelation`, which runs **one indexed SQL join** per call (`JDBCBackend.listEntitiesByRelation`). Its callers are all metadata governance managers:
+
+| Caller | Relation | API that uses it |
+| -------------------- | ---------------------------- |-----------------------------------|
+| `OwnerManager` | `OWNER_REL` | `GET .../owner` |
+| `RoleManager` | role relations | role / authorization management |
+| `FutureGrantManager` | role/user/group relations | applying future grants (admin op) |
+| `TagManager` | `TAG_METADATA_OBJECT_REL` | tag endpoints |
+| `PolicyManager` | `POLICY_METADATA_OBJECT_REL` | policy endpoints |
+
+**Who does not.** The two paths that must be fast do **not** use it:
+
+- **Core metadata reads** (`get` / `list` of table, schema, catalog, …) never call `listEntitiesByRelation`. Removing the relation cache does not affect them at all.
+- **Authorization checks** (`JcasbinAuthorizer`) read roles straight from mappers (`RoleMetaMapper.listRolesByUserId` / `listRolesByGroupId`), owner from its own `ownerRelCache` (which polls `owner_meta`), and id from its own `metadataIdCache`. It does not use the entity store relation cache at all. Relation caching was first added with authorization in mind, but authorization no longer uses it.
+
+**Cost of removing it.** Each call becomes one indexed query — not an N+1 (one query per item). No list endpoint loads relations per item in a loop. The one place a single request makes several queries is **tag / policy inheritance**: listing an object's tags also reads its parents (the object plus up to ~3 ancestors), so a tag lookup is up to ~4 single-row queries; the cache mainly saves re-reading popular parents. This is the only workload where removing the cache adds real DB load, and it can be measured today — those calls are already `@Monitored` (`baseMetricName = "listTagsForMetadataObject"`, `"getOwner"`, `"listPoliciesForMetadataObject"`).
+
+**Decision.** Remove relation caching from the entity store cache. Relation reads go straight to the DB (one indexed query each), the same as authorization already does. This is safe for the core read path and for authorization; the only risk is workloads with heavy tag/policy inheritance reads, which we can watch with the existing metrics and, if ever needed, address by adding precise relation caching back later.
+
+The result: the cache holds only **entity keys**, so cross-node invalidation becomes the easy one-to-one case, and (as both implementations show) each design loses its hardest part. The `ReverseIndexCache` and the two-direction relation keys are removed with it.
+
+But "cache only entity keys" is not the end of it: some entities **copy fields from other entities**, which would bring the reverse-lookup problem back. The next section works out which entities are actually safe to cache.
+
+---
+
+## Which Entities to Cache
+
+Dropping relations leaves the entity keys. But not every entity key is truly one-to-one. Some entities store fields **copied from other entities**, and those copies go stale when the other entity changes — which brings back the same reverse lookup we just removed. So we look at what each cached entity actually holds.
+
+**Self-contained vs. derived.**
+
+| Entity | Copies a field from another entity? | Safe to cache on its own? |
+| ------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------- |
+| metalake, catalog, schema, table, topic, model, view, fileset | no — holds only its own data (columns, properties, comment…) | yes |
+| tag, policy | no — associations are relations, not stored on the entity | yes |
+| user, group | yes — `roleNames` / `roleIds`, built from the user's roles | no |
+| role | yes — `securableObjects`, built from metadata objects | no |
+
+**Why user / group / role are a problem.**
+
+- `getUserByIdentifier` builds `roleNames` at read time by joining the user's roles (`UserMetaService` calls `RoleMetaService.listRolesByUserId`). If a role is dropped, it disappears from every user's list, but the user rows are not touched — so a cached user still lists the dropped role. Finding which users hold a role is a reverse lookup (role → users), exactly what dropping relations was meant to avoid.
+- `RoleEntity.securableObjects` has the same shape one level up: if a metadata object is renamed or dropped, a cached role that points at it is stale, and finding which roles point at an object is again a reverse lookup (object → roles).
+
+**Does authorization need these in the cache?** This is the key question, because authorization is the hot path. We checked `JcasbinAuthorizer`:
+
+- **user / group — no.** It reads user and group data through its own mappers (`UserMetaMapper`, `GroupMetaMapper`) into its own caches (`userRoleCache`, `groupRoleCache`), never through the entity store cache. So excluding user/group from the entity store cache does not affect authorization at all.
+- **role — only at cold start or after a change.** It does read role entities through the entity store (`entityStore.batchGet/get(ROLE)`), but only to (re)load a role's policies into the enforcer. Loaded roles are held in `loadedRoles`, a cache with `expireAfterAccess` (default 1 hour), so a role used at least once an hour never expires and the entity read is skipped. The entity read happens only on cold start, right after a role is edited, or after a role sits unused for over an hour — each a cheap one-time `batchGet`, not a per-request cost.
+
+So caching user, group, and role buys almost nothing (authorization does not depend on it) and costs a lot (the reverse-lookup problem comes back). tag and policy are safe to cache, but they are low-volume governance objects, not the read-heavy metadata the cache exists for.
+
+**Conclusion: cache only the basic metadata objects** — metalake, catalog, schema, table, topic, model, view, fileset. In code this is a small allowlist of entity types in the cache. Every cached entity is then self-contained and one-to-one, so cross-node invalidation stays precise with no reverse lookups. As a bonus, these entities already write ALTER/DROP rows to `entity_change_log`, so the writer side needs no change at all.
+
+The cache now holds only self-contained metadata objects. The next question is how to tell the other nodes to drop a key when it changes.
Review Comment:
There has been a relatively long-standing problem. Currently, due to the introduction of relation in the entity store cache, the overall design has deviated from the original intention of being simple and pluggable. It has become so complex, with the addition of prefix indexes and reverse indexes to maintain the complex relation model. It is impossible for users to introduce a new reliable implementation in a short period of time. So it is inevitable to return to a simple design; otherwise, it would be impossible to achieve plug-and-pull functionality.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3543986745
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -0,0 +1,350 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+---
+title: "Multi-Node Support for the Entity Store Cache"
+status: "Draft"
+date: "2026-07-07"
+---
+
+## Background
+
+Gravitino has two caches:
+
+- The **jcasbin authorization cache** already works with more than one node.
+- The **entity store cache** does not. When a change happens on node A, only node A clears its cache. Node B keeps serving the old data until its entry expires.
+
+Because of this, the only safe way to run more than one node today is to turn the entity store cache off (`gravitino.cache.enabled=false`). That is bad for read-heavy catalogs, especially Iceberg.
+
+This document proposes a design to make the entity store cache correct when running more than one node. It is a design proposal; no behavior has changed yet.
+
+## Goals and Non-Goals
+
+**Goals**
+
+- Make the entity store cache correct with more than one node, so `gravitino.cache.enabled=true` is safe.
+- Keep the cache **pluggable**: one SPI, chosen by `gravitino.cache.impl`. Ship `caffeine` as the default (no extra dependency) and `redis` as an option the user turns on by config.
+- Keep single-node behavior and the write path (the optimistic version lock) unchanged.
+
+**Non-Goals**
+
+- Replace the entity store or its write path. The cache sits in front of the store and is never the source of truth.
+- Add a cluster membership / gossip layer or any other complex distributed system. We only use the DB Gravitino already needs, or the external cache the user turns on.
+
+---
+
+## Current Cache Implementation
+
+`EntityCache` is already an SPI, chosen by `gravitino.cache.impl` and created by `CacheFactory`. There is one implementation today, `CaffeineEntityCache` (`caffeine`): an in-memory cache, **one copy per node**, with two kinds of entries:
+
+- **entity keys** `(ident, type)` → the entity itself;
+- **relation keys** `(ident, type, relType)` → the list of related entities, stored **in both directions** and kept in step by an in-process **reverse index** (`ReverseIndexCache`).
+
+On a write, the node clears the changed key and then uses the reverse index to clear the related keys. On a single node this is correct. The problem is that this clearing happens **only on the node that made the change** (`RelationalEntityStore` calls `cache.invalidate(...)` locally). Nothing tells the other nodes, so they serve old data until their entries expire.
+
+Some behavior is already safe with more than one node and does not change:
+
+| Already correct | Why |
+| ------------------------- | ---------------------------------------------------------------------------- |
+| Writes never lose updates | The write path reads the DB (not the cache) with an optimistic version check |
+| `list(namespace)` | Skips the cache, so it is never stale |
+| CREATE | Needs nothing: no negative caching, and `list` skips the cache |
+
+The rest of the problem splits in two:
+
+- **entity keys** are one-to-one. "table T changed" names exactly the key to drop, and any node can drop it. This is easy.
+- **relation keys** have a reverse key. Dropping one side (say a role) also means dropping the other side's key (each user that had the role), but "the role changed" does not say *which* users those are. The writing node knows them from its local reverse index; a remote node may not.
+
+That reverse key is the hard part. So the first question is whether the cache needs relations at all.
+
+---
+
+## Do We Need to Cache Relations?
+
+All the cross-node difficulty comes from relation caching (the reverse key and the write fan-out). Before building around it, we checked whether it is actually important for performance. It is not.
+
+**Who reads the relation cache.** The cached relation path is `RelationalEntityStore.listEntitiesByRelation`, which runs **one indexed SQL join** per call (`JDBCBackend.listEntitiesByRelation`). Its callers are all metadata governance managers:
+
+| Caller | Relation | API that uses it |
+| -------------------- | ---------------------------- |-----------------------------------|
+| `OwnerManager` | `OWNER_REL` | `GET .../owner` |
+| `RoleManager` | role relations | role / authorization management |
+| `FutureGrantManager` | role/user/group relations | applying future grants (admin op) |
+| `TagManager` | `TAG_METADATA_OBJECT_REL` | tag endpoints |
+| `PolicyManager` | `POLICY_METADATA_OBJECT_REL` | policy endpoints |
+
+**Who does not.** The two paths that must be fast do **not** use it:
+
+- **Core metadata reads** (`get` / `list` of table, schema, catalog, …) never call `listEntitiesByRelation`. Removing the relation cache does not affect them at all.
+- **Authorization checks** (`JcasbinAuthorizer`) read roles straight from mappers (`RoleMetaMapper.listRolesByUserId` / `listRolesByGroupId`), owner from its own `ownerRelCache` (which polls `owner_meta`), and id from its own `metadataIdCache`. It does not use the entity store relation cache at all. Relation caching was first added with authorization in mind, but authorization no longer uses it.
+
+**Cost of removing it.** Each call becomes one indexed query — not an N+1 (one query per item). No list endpoint loads relations per item in a loop. The one place a single request makes several queries is **tag / policy inheritance**: listing an object's tags also reads its parents (the object plus up to ~3 ancestors), so a tag lookup is up to ~4 single-row queries; the cache mainly saves re-reading popular parents. This is the only workload where removing the cache adds real DB load, and it can be measured today — those calls are already `@Monitored` (`baseMetricName = "listTagsForMetadataObject"`, `"getOwner"`, `"listPoliciesForMetadataObject"`).
+
+**Decision.** Remove relation caching from the entity store cache. Relation reads go straight to the DB (one indexed query each), the same as authorization already does. This is safe for the core read path and for authorization; the only risk is workloads with heavy tag/policy inheritance reads, which we can watch with the existing metrics and, if ever needed, address by adding precise relation caching back later.
+
+The result: the cache holds only **entity keys**, so cross-node invalidation becomes the easy one-to-one case, and (as both implementations show) each design loses its hardest part. The `ReverseIndexCache` and the two-direction relation keys are removed with it.
+
+But "cache only entity keys" is not the end of it: some entities **copy fields from other entities**, which would bring the reverse-lookup problem back. The next section works out which entities are actually safe to cache.
+
+---
+
+## Which Entities to Cache
+
+Dropping relations leaves the entity keys. But not every entity key is truly one-to-one. Some entities store fields **copied from other entities**, and those copies go stale when the other entity changes — which brings back the same reverse lookup we just removed. So we look at what each cached entity actually holds.
+
+**Self-contained vs. derived.**
+
+| Entity | Copies a field from another entity? | Safe to cache on its own? |
+| ------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------- |
+| metalake, catalog, schema, table, topic, model, view, fileset | no — holds only its own data (columns, properties, comment…) | yes |
+| tag, policy | no — associations are relations, not stored on the entity | yes |
+| user, group | yes — `roleNames` / `roleIds`, built from the user's roles | no |
+| role | yes — `securableObjects`, built from metadata objects | no |
+
+**Why user / group / role are a problem.**
+
+- `getUserByIdentifier` builds `roleNames` at read time by joining the user's roles (`UserMetaService` calls `RoleMetaService.listRolesByUserId`). If a role is dropped, it disappears from every user's list, but the user rows are not touched — so a cached user still lists the dropped role. Finding which users hold a role is a reverse lookup (role → users), exactly what dropping relations was meant to avoid.
+- `RoleEntity.securableObjects` has the same shape one level up: if a metadata object is renamed or dropped, a cached role that points at it is stale, and finding which roles point at an object is again a reverse lookup (object → roles).
+
+**Does authorization need these in the cache?** This is the key question, because authorization is the hot path. We checked `JcasbinAuthorizer`:
+
+- **user / group — no.** It reads user and group data through its own mappers (`UserMetaMapper`, `GroupMetaMapper`) into its own caches (`userRoleCache`, `groupRoleCache`), never through the entity store cache. So excluding user/group from the entity store cache does not affect authorization at all.
+- **role — only at cold start or after a change.** It does read role entities through the entity store (`entityStore.batchGet/get(ROLE)`), but only to (re)load a role's policies into the enforcer. Loaded roles are held in `loadedRoles`, a cache with `expireAfterAccess` (default 1 hour), so a role used at least once an hour never expires and the entity read is skipped. The entity read happens only on cold start, right after a role is edited, or after a role sits unused for over an hour — each a cheap one-time `batchGet`, not a per-request cost.
+
+So caching user, group, and role buys almost nothing (authorization does not depend on it) and costs a lot (the reverse-lookup problem comes back). tag and policy are safe to cache, but they are low-volume governance objects, not the read-heavy metadata the cache exists for.
+
+**Conclusion: cache only the basic metadata objects** — metalake, catalog, schema, table, topic, model, view, fileset. In code this is a small allowlist of entity types in the cache. Every cached entity is then self-contained and one-to-one, so cross-node invalidation stays precise with no reverse lookups. As a bonus, these entities already write ALTER/DROP rows to `entity_change_log`, so the writer side needs no change at all.
Review Comment:
Yeah, it should also be considered, sorry to omit it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3584928039
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -252,54 +254,68 @@ The entity store cache becomes a third consumer of the poller, next to the catal
### Consistency
-The cache is never the source of truth. The write path always reads the DB under the optimistic version lock, so eventual consistency can **never** cause a lost update or corrupt data. Its only observable effect is **bounded read staleness on non-writing nodes**: for up to one poll interval, a node other than the writer may serve an older value.
+The cache never holds the truth. Every write goes to the DB first, under the version lock, so a stale cache can **never** cause a lost update or a bad write. The only thing that can go wrong is that a read on **another node** returns an old value for a short time — at most one poll interval, until that node drops the key.
-- **Other nodes:** eventual — an entity key is dropped within one poll interval of the change.
-- **Writing node:** unchanged — it still clears its own cache on the write path, so it reads its own writes right away. Its own row is replayed later, which does nothing (clearing an already-clear key is a no-op).
-- **Write path:** unchanged — it reads the DB with the optimistic version check.
+So the real question is simple: when another node reads an old value, does it matter? We went through every alter and every drop, for every cached entity, one at a time. A stale read falls into one of two buckets:
-The rest of this section works through every way that staleness window can be observed, and how each is handled.
+- **The old value makes the next step fail with an error.** The user sees the error and tries again. This is safe.
+- **The old value is used silently and gives a wrong answer, with no error.** This is the dangerous kind.
-#### Staleness scenarios and mitigations
+We only need to worry about the second bucket.
-**1. Plain stale read (bounded, mostly tolerable).**
+#### Two groups of cached entities
-| # | Scenario | Effect | Possible mitigation |
-| - | -------------------------------------------------------------- |-----------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------|
-| 1 | Node A ALTERs a table (add column); B GETs it | B serves the old schema for up to one poll interval | Accept within the SLA window; a caller that needs an exact schema uses a consistent (cache-bypass) read |
-| 2 | Node A DROPs a table; B GETs it | B still reports it as present (cache hit) until the next poll | Accept — any write to it on B is re-validated against the DB and rejected as not-found, so no corruption |
-| 3 | RENAME (the old name behaves like a DROP); B GETs the old name | B keeps resolving the old name until the next poll; the new name misses → DB load | Same as DROP — bounded by the poll interval |
-| 4 | A property changes (e.g. Iceberg metadata-location); B GETs it | B returns the old location → a query on B may read an old snapshot/path | Highest-value case: offer a consistent (cache-bypass) read for location-sensitive callers, or use `redis` |
+The danger depends on where the real data comes from.
-**2. Read-your-writes across nodes.**
+**Group 1 — the data comes from the connector: table, view, topic, and schemas in external catalogs.** For these, Gravitino does not read the metadata from its own cache. On every load it asks the underlying system (Hive, Iceberg, JDBC, Kafka) for the current object, and uses the cached entity only for Gravitino's own id and audit fields. All nodes ask the same underlying system, so they all see the same thing. If the object was dropped or renamed, the connector call fails right away with a "not found" error. **This whole group is safe — nothing to do.**
-| # | Scenario | Effect | Possible mitigation |
-| - |---------------------------------------------------------------------|-------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
-| 5 | Through a load balancer, ALTER on A then an immediate read on B | Stale — violates session consistency; without sticky routing the change looks lost | Sticky sessions at the LB, or a client-supplied last-seen version that bypasses the cache when the copy is older; `redis` removes it entirely |
-| 6 | CREATE (rather than ALTER/DROP) | No problem — no negative caching and `list` skips the cache, so a new entity is visible at once | None needed |
+**Group 2 — the data comes from Gravitino's own store: metalake, catalog, managed schema, fileset, model, model version, function.** Here the cached entity *is* the answer, so a stale read really can return an old value. We looked at each alter in this group.
-**3. Cross-node read-modify-write.**
+(Views follow the same rule as tables: their definition is read through the connector on every load, so they sit in Group 1 and are safe.)
-| # | Scenario | Effect | Possible mitigation |
-| - | ------------------------------------------------------------------------------------- |-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------|
-| 7 | B reads stale value A and submits an update carrying A's version as the expected one | The optimistic lock rejects it on version mismatch — safe, but the user sees an unexpected conflict | Accept (correctness is preserved); reduce its frequency with the read-your-writes mitigations above |
+#### Walking through the alters in Group 2
-**4. Is the window actually bounded? — poller reliability (the real risk).** The "at most one poll interval" guarantee holds **only if the poller never drops a row**. If it does, the stale entry survives until the cache TTL, so this is the one place eventual consistency itself can break.
+Most alters are safe:
-| # | Scenario | Effect | Possible mitigation |
-| -- |-----------------------------------------------------------------------------------------------------------|-----------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------|
-| 8 | Commit-ordering gap / a skipped row | The key is never invalidated; stale until the TTL | Reuse the lag-safe, id-based polling already built for the change log (`#11736`); keep the cache TTL as a backstop |
-| 9 | Poller thread dies / DB briefly unreachable | That node serves stale data until the TTL | TTL backstop + monitor poller liveness/lag and alert |
-| 10 | Hierarchical DROP: only the container (schema) emits a row; children are cleared by a forward prefix scan | Correct as long as the prefix scan covers every child key | Cover with the hierarchical-drop test; confirm no child is written in a separate transaction that outlives the container row |
+| Change | What a stale read does | Safe? |
+| -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
+| rename (metalake, catalog, schema, fileset, model) | reading the old name returns a leftover copy, but any write to it goes to the DB and fails; the new name misses the cache and loads fresh from the DB | yes |
+| update comment | you see an old comment for a moment | yes |
+| set / remove property (metalake, model, fileset) | these properties do not change where the data lives | yes |
+| fileset storage location | **cannot be changed** — there is no alter for it, so it can never go stale | yes |
+| drop | for Group 1 the connector call fails; for a fileset the file path is gone and access fails | yes |
+| catalog changes | already handled today by a separate cross-node signal (`CatalogChangeLogListener`), not by this cache | yes |
-**5. Idempotency (no issue).** Replaying ALTER then DROP, in any order or duplicated, is safe: invalidation is idempotent, so out-of-order or repeated replay has no effect.
+Five cases are **not** safe — a stale read gives a wrong answer with no error. They are in the model area, functions, or the metalake on/off flag:
-#### Summary: main risks, resolutions, and the staleness SLA
+| Change | Why a stale read is wrong, with no error |
+| --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| model version — update / add / remove URI | the URI points to the model files. An old URI silently loads the **wrong model files**. |
+| model version — update aliases | an alias silently points to the **wrong version**. |
+| model — latest version (after a new version is added on another node) | "get the latest version" silently returns an **old version**. |
+| function — add / update / remove implementation or definition | the implementation is the code the function runs. An old copy silently runs the **wrong function code**. |
Review Comment:
For the model, functions, potential consistency problems will happen, so I'm going to disable them temporarily, and I could not find a good solution to avoid the defect during the refresh window.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3557533644
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -252,10 +252,55 @@ The entity store cache becomes a third consumer of the poller, next to the catal
### Consistency
+The cache is never the source of truth. The write path always reads the DB under the optimistic version lock, so eventual consistency can **never** cause a lost update or corrupt data. Its only observable effect is **bounded read staleness on non-writing nodes**: for up to one poll interval, a node other than the writer may serve an older value.
+
- **Other nodes:** eventual — an entity key is dropped within one poll interval of the change.
- **Writing node:** unchanged — it still clears its own cache on the write path, so it reads its own writes right away. Its own row is replayed later, which does nothing (clearing an already-clear key is a no-op).
- **Write path:** unchanged — it reads the DB with the optimistic version check.
+The rest of this section works through every way that staleness window can be observed, and how each is handled.
+
+#### Staleness scenarios and mitigations
+
+**1. Plain stale read (bounded, mostly tolerable).**
+
+| # | Scenario | Effect | Possible mitigation |
+| - | -------------------------------------------------------------- |-----------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------|
+| 1 | Node A ALTERs a table (add column); B GETs it | B serves the old schema for up to one poll interval | Accept within the SLA window; a caller that needs an exact schema uses a consistent (cache-bypass) read |
+| 2 | Node A DROPs a table; B GETs it | B still reports it as present (cache hit) until the next poll | Accept — any write to it on B is re-validated against the DB and rejected as not-found, so no corruption |
+| 3 | RENAME (the old name behaves like a DROP); B GETs the old name | B keeps resolving the old name until the next poll; the new name misses → DB load | Same as DROP — bounded by the poll interval |
+| 4 | A property changes (e.g. Iceberg metadata-location); B GETs it | B returns the old location → a query on B may read an old snapshot/path | Highest-value case: offer a consistent (cache-bypass) read for location-sensitive callers, or use `redis` |
Review Comment:
I think you should consider all the supported "alter" scenarios for all the cached entities. To see if such a case will lead to the unexpected scenario. If so, we should introduce db version checking like authorization cache.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#issuecomment-5031464882
@jerryshao
If the document is generally okay with you, can you merge it when you have time, and then I can continue to push implementation PRs to merge.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3613966998
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -252,54 +254,68 @@ The entity store cache becomes a third consumer of the poller, next to the catal
### Consistency
-The cache is never the source of truth. The write path always reads the DB under the optimistic version lock, so eventual consistency can **never** cause a lost update or corrupt data. Its only observable effect is **bounded read staleness on non-writing nodes**: for up to one poll interval, a node other than the writer may serve an older value.
+The cache never holds the truth. Every write goes to the DB first, under the version lock, so a stale cache can **never** cause a lost update or a bad write. The only thing that can go wrong is that a read on **another node** returns an old value for a short time — at most one poll interval, until that node drops the key.
-- **Other nodes:** eventual — an entity key is dropped within one poll interval of the change.
-- **Writing node:** unchanged — it still clears its own cache on the write path, so it reads its own writes right away. Its own row is replayed later, which does nothing (clearing an already-clear key is a no-op).
-- **Write path:** unchanged — it reads the DB with the optimistic version check.
+So the real question is simple: when another node reads an old value, does it matter? We went through every alter and every drop, for every cached entity, one at a time. A stale read falls into one of two buckets:
-The rest of this section works through every way that staleness window can be observed, and how each is handled.
+- **The old value makes the next step fail with an error.** The user sees the error and tries again. This is safe.
+- **The old value is used silently and gives a wrong answer, with no error.** This is the dangerous kind.
-#### Staleness scenarios and mitigations
+We only need to worry about the second bucket.
-**1. Plain stale read (bounded, mostly tolerable).**
+#### Two groups of cached entities
-| # | Scenario | Effect | Possible mitigation |
-| - | -------------------------------------------------------------- |-----------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------|
-| 1 | Node A ALTERs a table (add column); B GETs it | B serves the old schema for up to one poll interval | Accept within the SLA window; a caller that needs an exact schema uses a consistent (cache-bypass) read |
-| 2 | Node A DROPs a table; B GETs it | B still reports it as present (cache hit) until the next poll | Accept — any write to it on B is re-validated against the DB and rejected as not-found, so no corruption |
-| 3 | RENAME (the old name behaves like a DROP); B GETs the old name | B keeps resolving the old name until the next poll; the new name misses → DB load | Same as DROP — bounded by the poll interval |
-| 4 | A property changes (e.g. Iceberg metadata-location); B GETs it | B returns the old location → a query on B may read an old snapshot/path | Highest-value case: offer a consistent (cache-bypass) read for location-sensitive callers, or use `redis` |
+The danger depends on where the real data comes from.
-**2. Read-your-writes across nodes.**
+**Group 1 — the data comes from the connector: table, view, topic, and schemas in external catalogs.** For these, Gravitino does not read the metadata from its own cache. On every load it asks the underlying system (Hive, Iceberg, JDBC, Kafka) for the current object, and uses the cached entity only for Gravitino's own id and audit fields. All nodes ask the same underlying system, so they all see the same thing. If the object was dropped or renamed, the connector call fails right away with a "not found" error. **This whole group is safe — nothing to do.**
-| # | Scenario | Effect | Possible mitigation |
-| - |---------------------------------------------------------------------|-------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
-| 5 | Through a load balancer, ALTER on A then an immediate read on B | Stale — violates session consistency; without sticky routing the change looks lost | Sticky sessions at the LB, or a client-supplied last-seen version that bypasses the cache when the copy is older; `redis` removes it entirely |
-| 6 | CREATE (rather than ALTER/DROP) | No problem — no negative caching and `list` skips the cache, so a new entity is visible at once | None needed |
+**Group 2 — the data comes from Gravitino's own store: metalake, catalog, managed schema, fileset, model, model version, function.** Here the cached entity *is* the answer, so a stale read really can return an old value. We looked at each alter in this group.
-**3. Cross-node read-modify-write.**
+(Views follow the same rule as tables: their definition is read through the connector on every load, so they sit in Group 1 and are safe.)
-| # | Scenario | Effect | Possible mitigation |
-| - | ------------------------------------------------------------------------------------- |-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------|
-| 7 | B reads stale value A and submits an update carrying A's version as the expected one | The optimistic lock rejects it on version mismatch — safe, but the user sees an unexpected conflict | Accept (correctness is preserved); reduce its frequency with the read-your-writes mitigations above |
+#### Walking through the alters in Group 2
-**4. Is the window actually bounded? — poller reliability (the real risk).** The "at most one poll interval" guarantee holds **only if the poller never drops a row**. If it does, the stale entry survives until the cache TTL, so this is the one place eventual consistency itself can break.
+Most alters are safe:
-| # | Scenario | Effect | Possible mitigation |
-| -- |-----------------------------------------------------------------------------------------------------------|-----------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------|
-| 8 | Commit-ordering gap / a skipped row | The key is never invalidated; stale until the TTL | Reuse the lag-safe, id-based polling already built for the change log (`#11736`); keep the cache TTL as a backstop |
-| 9 | Poller thread dies / DB briefly unreachable | That node serves stale data until the TTL | TTL backstop + monitor poller liveness/lag and alert |
-| 10 | Hierarchical DROP: only the container (schema) emits a row; children are cleared by a forward prefix scan | Correct as long as the prefix scan covers every child key | Cover with the hierarchical-drop test; confirm no child is written in a separate transaction that outlives the container row |
+| Change | What a stale read does | Safe? |
+| -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
+| rename (metalake, catalog, schema, fileset, model) | reading the old name returns a leftover copy, but any write to it goes to the DB and fails; the new name misses the cache and loads fresh from the DB | yes |
+| update comment | you see an old comment for a moment | yes |
+| set / remove property (metalake, model, fileset) | these properties do not change where the data lives | yes |
+| fileset storage location | **cannot be changed** — there is no alter for it, so it can never go stale | yes |
+| drop | for Group 1 the connector call fails; for a fileset the file path is gone and access fails | yes |
+| catalog changes | already handled today by a separate cross-node signal (`CatalogChangeLogListener`), not by this cache | yes |
-**5. Idempotency (no issue).** Replaying ALTER then DROP, in any order or duplicated, is safe: invalidation is idempotent, so out-of-order or repeated replay has no effect.
+Five cases are **not** safe — a stale read gives a wrong answer with no error. They are in the model area, functions, or the metalake on/off flag:
-#### Summary: main risks, resolutions, and the staleness SLA
+| Change | Why a stale read is wrong, with no error |
+| --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| model version — update / add / remove URI | the URI points to the model files. An old URI silently loads the **wrong model files**. |
+| model version — update aliases | an alias silently points to the **wrong version**. |
+| model — latest version (after a new version is added on another node) | "get the latest version" silently returns an **old version**. |
+| function — add / update / remove implementation or definition | the implementation is the code the function runs. An old copy silently runs the **wrong function code**. |
+| metalake — disable | a node with a stale copy still thinks the metalake is on and **lets operations run** on a metalake that was turned off. (Turning it back on is safe: a stale node only throws "in use" by mistake.) |
Review Comment:
@roryqi
For the entity store cache, the tag and policy will be cached as designed. If strong consistency is required for access control, I will modify it in the future.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3584630113
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -252,54 +254,68 @@ The entity store cache becomes a third consumer of the poller, next to the catal
### Consistency
-The cache is never the source of truth. The write path always reads the DB under the optimistic version lock, so eventual consistency can **never** cause a lost update or corrupt data. Its only observable effect is **bounded read staleness on non-writing nodes**: for up to one poll interval, a node other than the writer may serve an older value.
+The cache never holds the truth. Every write goes to the DB first, under the version lock, so a stale cache can **never** cause a lost update or a bad write. The only thing that can go wrong is that a read on **another node** returns an old value for a short time — at most one poll interval, until that node drops the key.
-- **Other nodes:** eventual — an entity key is dropped within one poll interval of the change.
-- **Writing node:** unchanged — it still clears its own cache on the write path, so it reads its own writes right away. Its own row is replayed later, which does nothing (clearing an already-clear key is a no-op).
-- **Write path:** unchanged — it reads the DB with the optimistic version check.
+So the real question is simple: when another node reads an old value, does it matter? We went through every alter and every drop, for every cached entity, one at a time. A stale read falls into one of two buckets:
-The rest of this section works through every way that staleness window can be observed, and how each is handled.
+- **The old value makes the next step fail with an error.** The user sees the error and tries again. This is safe.
+- **The old value is used silently and gives a wrong answer, with no error.** This is the dangerous kind.
-#### Staleness scenarios and mitigations
+We only need to worry about the second bucket.
-**1. Plain stale read (bounded, mostly tolerable).**
+#### Two groups of cached entities
-| # | Scenario | Effect | Possible mitigation |
-| - | -------------------------------------------------------------- |-----------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------|
-| 1 | Node A ALTERs a table (add column); B GETs it | B serves the old schema for up to one poll interval | Accept within the SLA window; a caller that needs an exact schema uses a consistent (cache-bypass) read |
-| 2 | Node A DROPs a table; B GETs it | B still reports it as present (cache hit) until the next poll | Accept — any write to it on B is re-validated against the DB and rejected as not-found, so no corruption |
-| 3 | RENAME (the old name behaves like a DROP); B GETs the old name | B keeps resolving the old name until the next poll; the new name misses → DB load | Same as DROP — bounded by the poll interval |
-| 4 | A property changes (e.g. Iceberg metadata-location); B GETs it | B returns the old location → a query on B may read an old snapshot/path | Highest-value case: offer a consistent (cache-bypass) read for location-sensitive callers, or use `redis` |
+The danger depends on where the real data comes from.
-**2. Read-your-writes across nodes.**
+**Group 1 — the data comes from the connector: table, view, topic, and schemas in external catalogs.** For these, Gravitino does not read the metadata from its own cache. On every load it asks the underlying system (Hive, Iceberg, JDBC, Kafka) for the current object, and uses the cached entity only for Gravitino's own id and audit fields. All nodes ask the same underlying system, so they all see the same thing. If the object was dropped or renamed, the connector call fails right away with a "not found" error. **This whole group is safe — nothing to do.**
-| # | Scenario | Effect | Possible mitigation |
-| - |---------------------------------------------------------------------|-------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
-| 5 | Through a load balancer, ALTER on A then an immediate read on B | Stale — violates session consistency; without sticky routing the change looks lost | Sticky sessions at the LB, or a client-supplied last-seen version that bypasses the cache when the copy is older; `redis` removes it entirely |
-| 6 | CREATE (rather than ALTER/DROP) | No problem — no negative caching and `list` skips the cache, so a new entity is visible at once | None needed |
+**Group 2 — the data comes from Gravitino's own store: metalake, catalog, managed schema, fileset, model, model version, function.** Here the cached entity *is* the answer, so a stale read really can return an old value. We looked at each alter in this group.
-**3. Cross-node read-modify-write.**
+(Views follow the same rule as tables: their definition is read through the connector on every load, so they sit in Group 1 and are safe.)
-| # | Scenario | Effect | Possible mitigation |
-| - | ------------------------------------------------------------------------------------- |-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------|
-| 7 | B reads stale value A and submits an update carrying A's version as the expected one | The optimistic lock rejects it on version mismatch — safe, but the user sees an unexpected conflict | Accept (correctness is preserved); reduce its frequency with the read-your-writes mitigations above |
+#### Walking through the alters in Group 2
-**4. Is the window actually bounded? — poller reliability (the real risk).** The "at most one poll interval" guarantee holds **only if the poller never drops a row**. If it does, the stale entry survives until the cache TTL, so this is the one place eventual consistency itself can break.
+Most alters are safe:
-| # | Scenario | Effect | Possible mitigation |
-| -- |-----------------------------------------------------------------------------------------------------------|-----------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------|
-| 8 | Commit-ordering gap / a skipped row | The key is never invalidated; stale until the TTL | Reuse the lag-safe, id-based polling already built for the change log (`#11736`); keep the cache TTL as a backstop |
-| 9 | Poller thread dies / DB briefly unreachable | That node serves stale data until the TTL | TTL backstop + monitor poller liveness/lag and alert |
-| 10 | Hierarchical DROP: only the container (schema) emits a row; children are cleared by a forward prefix scan | Correct as long as the prefix scan covers every child key | Cover with the hierarchical-drop test; confirm no child is written in a separate transaction that outlives the container row |
+| Change | What a stale read does | Safe? |
+| -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
+| rename (metalake, catalog, schema, fileset, model) | reading the old name returns a leftover copy, but any write to it goes to the DB and fails; the new name misses the cache and loads fresh from the DB | yes |
+| update comment | you see an old comment for a moment | yes |
+| set / remove property (metalake, model, fileset) | these properties do not change where the data lives | yes |
+| fileset storage location | **cannot be changed** — there is no alter for it, so it can never go stale | yes |
+| drop | for Group 1 the connector call fails; for a fileset the file path is gone and access fails | yes |
+| catalog changes | already handled today by a separate cross-node signal (`CatalogChangeLogListener`), not by this cache | yes |
-**5. Idempotency (no issue).** Replaying ALTER then DROP, in any order or duplicated, is safe: invalidation is idempotent, so out-of-order or repeated replay has no effect.
+Five cases are **not** safe — a stale read gives a wrong answer with no error. They are in the model area, functions, or the metalake on/off flag:
-#### Summary: main risks, resolutions, and the staleness SLA
+| Change | Why a stale read is wrong, with no error |
+| --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| model version — update / add / remove URI | the URI points to the model files. An old URI silently loads the **wrong model files**. |
+| model version — update aliases | an alias silently points to the **wrong version**. |
+| model — latest version (after a new version is added on another node) | "get the latest version" silently returns an **old version**. |
+| function — add / update / remove implementation or definition | the implementation is the code the function runs. An old copy silently runs the **wrong function code**. |
Review Comment:
Will you do the cache for these scenarios?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#issuecomment-5031854577
> @jerryshao If the document is generally okay with you, can you merge it when you have time, and then I can continue to push implementation PRs to merge.
OK, I will review it today.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3614007267
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -252,54 +254,68 @@ The entity store cache becomes a third consumer of the poller, next to the catal
### Consistency
-The cache is never the source of truth. The write path always reads the DB under the optimistic version lock, so eventual consistency can **never** cause a lost update or corrupt data. Its only observable effect is **bounded read staleness on non-writing nodes**: for up to one poll interval, a node other than the writer may serve an older value.
+The cache never holds the truth. Every write goes to the DB first, under the version lock, so a stale cache can **never** cause a lost update or a bad write. The only thing that can go wrong is that a read on **another node** returns an old value for a short time — at most one poll interval, until that node drops the key.
-- **Other nodes:** eventual — an entity key is dropped within one poll interval of the change.
-- **Writing node:** unchanged — it still clears its own cache on the write path, so it reads its own writes right away. Its own row is replayed later, which does nothing (clearing an already-clear key is a no-op).
-- **Write path:** unchanged — it reads the DB with the optimistic version check.
+So the real question is simple: when another node reads an old value, does it matter? We went through every alter and every drop, for every cached entity, one at a time. A stale read falls into one of two buckets:
-The rest of this section works through every way that staleness window can be observed, and how each is handled.
+- **The old value makes the next step fail with an error.** The user sees the error and tries again. This is safe.
+- **The old value is used silently and gives a wrong answer, with no error.** This is the dangerous kind.
-#### Staleness scenarios and mitigations
+We only need to worry about the second bucket.
-**1. Plain stale read (bounded, mostly tolerable).**
+#### Two groups of cached entities
-| # | Scenario | Effect | Possible mitigation |
-| - | -------------------------------------------------------------- |-----------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------|
-| 1 | Node A ALTERs a table (add column); B GETs it | B serves the old schema for up to one poll interval | Accept within the SLA window; a caller that needs an exact schema uses a consistent (cache-bypass) read |
-| 2 | Node A DROPs a table; B GETs it | B still reports it as present (cache hit) until the next poll | Accept — any write to it on B is re-validated against the DB and rejected as not-found, so no corruption |
-| 3 | RENAME (the old name behaves like a DROP); B GETs the old name | B keeps resolving the old name until the next poll; the new name misses → DB load | Same as DROP — bounded by the poll interval |
-| 4 | A property changes (e.g. Iceberg metadata-location); B GETs it | B returns the old location → a query on B may read an old snapshot/path | Highest-value case: offer a consistent (cache-bypass) read for location-sensitive callers, or use `redis` |
+The danger depends on where the real data comes from.
-**2. Read-your-writes across nodes.**
+**Group 1 — the data comes from the connector: table, view, topic, and schemas in external catalogs.** For these, Gravitino does not read the metadata from its own cache. On every load it asks the underlying system (Hive, Iceberg, JDBC, Kafka) for the current object, and uses the cached entity only for Gravitino's own id and audit fields. All nodes ask the same underlying system, so they all see the same thing. If the object was dropped or renamed, the connector call fails right away with a "not found" error. **This whole group is safe — nothing to do.**
-| # | Scenario | Effect | Possible mitigation |
-| - |---------------------------------------------------------------------|-------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
-| 5 | Through a load balancer, ALTER on A then an immediate read on B | Stale — violates session consistency; without sticky routing the change looks lost | Sticky sessions at the LB, or a client-supplied last-seen version that bypasses the cache when the copy is older; `redis` removes it entirely |
-| 6 | CREATE (rather than ALTER/DROP) | No problem — no negative caching and `list` skips the cache, so a new entity is visible at once | None needed |
+**Group 2 — the data comes from Gravitino's own store: metalake, catalog, managed schema, fileset, model, model version, function.** Here the cached entity *is* the answer, so a stale read really can return an old value. We looked at each alter in this group.
-**3. Cross-node read-modify-write.**
+(Views follow the same rule as tables: their definition is read through the connector on every load, so they sit in Group 1 and are safe.)
-| # | Scenario | Effect | Possible mitigation |
-| - | ------------------------------------------------------------------------------------- |-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------|
-| 7 | B reads stale value A and submits an update carrying A's version as the expected one | The optimistic lock rejects it on version mismatch — safe, but the user sees an unexpected conflict | Accept (correctness is preserved); reduce its frequency with the read-your-writes mitigations above |
+#### Walking through the alters in Group 2
-**4. Is the window actually bounded? — poller reliability (the real risk).** The "at most one poll interval" guarantee holds **only if the poller never drops a row**. If it does, the stale entry survives until the cache TTL, so this is the one place eventual consistency itself can break.
+Most alters are safe:
-| # | Scenario | Effect | Possible mitigation |
-| -- |-----------------------------------------------------------------------------------------------------------|-----------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------|
-| 8 | Commit-ordering gap / a skipped row | The key is never invalidated; stale until the TTL | Reuse the lag-safe, id-based polling already built for the change log (`#11736`); keep the cache TTL as a backstop |
-| 9 | Poller thread dies / DB briefly unreachable | That node serves stale data until the TTL | TTL backstop + monitor poller liveness/lag and alert |
-| 10 | Hierarchical DROP: only the container (schema) emits a row; children are cleared by a forward prefix scan | Correct as long as the prefix scan covers every child key | Cover with the hierarchical-drop test; confirm no child is written in a separate transaction that outlives the container row |
+| Change | What a stale read does | Safe? |
+| -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
+| rename (metalake, catalog, schema, fileset, model) | reading the old name returns a leftover copy, but any write to it goes to the DB and fails; the new name misses the cache and loads fresh from the DB | yes |
+| update comment | you see an old comment for a moment | yes |
+| set / remove property (metalake, model, fileset) | these properties do not change where the data lives | yes |
+| fileset storage location | **cannot be changed** — there is no alter for it, so it can never go stale | yes |
+| drop | for Group 1 the connector call fails; for a fileset the file path is gone and access fails | yes |
+| catalog changes | already handled today by a separate cross-node signal (`CatalogChangeLogListener`), not by this cache | yes |
-**5. Idempotency (no issue).** Replaying ALTER then DROP, in any order or duplicated, is safe: invalidation is idempotent, so out-of-order or repeated replay has no effect.
+Five cases are **not** safe — a stale read gives a wrong answer with no error. They are in the model area, functions, or the metalake on/off flag:
-#### Summary: main risks, resolutions, and the staleness SLA
+| Change | Why a stale read is wrong, with no error |
+| --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| model version — update / add / remove URI | the URI points to the model files. An old URI silently loads the **wrong model files**. |
+| model version — update aliases | an alias silently points to the **wrong version**. |
+| model — latest version (after a new version is added on another node) | "get the latest version" silently returns an **old version**. |
+| function — add / update / remove implementation or definition | the implementation is the code the function runs. An old copy silently runs the **wrong function code**. |
+| metalake — disable | a node with a stale copy still thinks the metalake is on and **lets operations run** on a metalake that was turned off. (Turning it back on is safe: a stale node only throws "in use" by mistake.) |
Review Comment:
One thing that needs to be noted is that the entity cache only stores a single entity, and relations will be removed as design. It will greatly impact tag/policy operations if it's called frequently. @roryqi
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3584995650
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -0,0 +1,412 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+---
+title: "Multi-Node Support for the Entity Store Cache"
+status: "Draft"
+date: "2026-07-07"
+---
+
+## Background
+
+Gravitino has two caches:
+
+- The **jcasbin authorization cache** already works with more than one node.
+- The **entity store cache** does not. When a change happens on node A, only node A clears its cache. Node B keeps serving the old data until its entry expires.
+
+Because of this, the only safe way to run more than one node today is to turn the entity store cache off (`gravitino.cache.enabled=false`). That is bad for read-heavy catalogs, especially Iceberg.
+
+This document proposes a design to make the entity store cache correct when running more than one node. It is a design proposal; no behavior has changed yet.
+
+## Goals and Non-Goals
+
+**Goals**
+
+- Make the entity store cache correct with more than one node, so `gravitino.cache.enabled=true` is safe.
+- Keep the cache **pluggable**: one SPI, chosen by `gravitino.cache.impl`. Ship `caffeine` as the default (no extra dependency) and `redis` as an option the user turns on by config. The current caffeine implementation is rather complex for any users to make any an new implementation, so we need to simplify it.
+- Keep single-node behavior and the write path (the optimistic version lock) unchanged.
+
+**Non-Goals**
+
+- Replace the entity store or its write path. The cache sits in front of the store and is never the source of truth.
+- Add a cluster membership / gossip layer or any other complex distributed system. We only use the DB Gravitino already needs, or the external cache the user turns on.
+
+---
+
+## Current Cache Implementation
+
+`EntityCache` is already an SPI, chosen by `gravitino.cache.impl` and created by `CacheFactory`. There is one implementation today, `CaffeineEntityCache` (`caffeine`): an in-memory cache, **one copy per node**, with two kinds of entries:
+
+- **entity keys** `(ident, type)` → the entity itself;
+- **relation keys** `(ident, type, relType)` → the list of related entities, stored **in both directions** and kept in step by an in-process **reverse index** (`ReverseIndexCache`).
+
+On a write, the node clears the changed key and then uses the reverse index to clear the related keys. On a single node this is correct. The problem is that this clearing happens **only on the node that made the change** (`RelationalEntityStore` calls `cache.invalidate(...)` locally). Nothing tells the other nodes, so they serve old data until their entries expire.
+
+Some behavior is already safe with more than one node and does not change:
+
+| Already correct | Why |
+| ------------------------- | ---------------------------------------------------------------------------- |
+| Writes never lose updates | The write path reads the DB (not the cache) with an optimistic version check |
+| `list(namespace)` | Skips the cache, so it is never stale |
+| CREATE | Needs nothing: no negative caching, and `list` skips the cache |
+
+The rest of the problem splits in two:
+
+- **entity keys** are one-to-one. "table T changed" names exactly the key to drop, and any node can drop it. This is easy.
+- **relation keys** have a reverse key. Dropping one side (say a role) also means dropping the other side's key (each user that had the role), but "the role changed" does not say *which* users those are. The writing node knows them from its local reverse index; a remote node may not.
+
+That reverse key is the hard part. So the first question is whether the cache needs relations at all.
+
+---
+
+## Do We Need to Cache Relations?
+
+All the cross-node difficulty comes from relation caching (the reverse key and the write fan-out). Before building around it, we checked whether it is actually important for performance. It is not.
+
+**Who reads the relation cache.** The cached relation path is `RelationalEntityStore.listEntitiesByRelation`, which runs **one indexed SQL join** per call (`JDBCBackend.listEntitiesByRelation`). Its callers are all metadata governance managers:
+
+| Caller | Relation | API that uses it |
+| -------------------- | ---------------------------- |-----------------------------------|
+| `OwnerManager` | `OWNER_REL` | `GET .../owner` |
+| `RoleManager` | role relations | role / authorization management |
+| `FutureGrantManager` | role/user/group relations | applying future grants (admin op) |
+| `TagManager` | `TAG_METADATA_OBJECT_REL` | tag endpoints |
+| `PolicyManager` | `POLICY_METADATA_OBJECT_REL` | policy endpoints |
+
+**Who does not.** The two paths that must be fast do **not** use it:
+
+- **Core metadata reads** (`get` / `list` of table, schema, catalog, …) never call `listEntitiesByRelation`. Removing the relation cache does not affect them at all.
+- **Authorization checks** (`JcasbinAuthorizer`) read roles straight from mappers (`RoleMetaMapper.listRolesByUserId` / `listRolesByGroupId`), owner from its own `ownerRelCache` (which polls `owner_meta`), and id from its own `metadataIdCache`. It does not use the entity store relation cache at all. Relation caching was first added with authorization in mind, but authorization no longer uses it.
+
+**Cost of removing it.** Each call becomes one indexed query — not an N+1 (one query per item). No list endpoint loads relations per item in a loop. The one place a single request makes several queries is **tag / policy inheritance**: listing an object's tags also reads its parents (the object plus up to ~3 ancestors), so a tag lookup is up to ~4 single-row queries; the cache mainly saves re-reading popular parents. This is the only workload where removing the cache adds real DB load, and it can be measured today — those calls are already `@Monitored` (`baseMetricName = "listTagsForMetadataObject"`, `"getOwner"`, `"listPoliciesForMetadataObject"`).
+
+**Decision.** Remove relation caching from the entity store cache. Relation reads go straight to the DB (one indexed query each), the same as authorization already does. This is safe for the core read path and for authorization; the only risk is workloads with heavy tag/policy inheritance reads, which we can watch with the existing metrics and, if ever needed, address by adding precise relation caching back later.
+
+The result: the cache holds only **entity keys**, so cross-node invalidation becomes the easy one-to-one case, and (as both implementations show) each design loses its hardest part. The `ReverseIndexCache` and the two-direction relation keys are removed with it.
+
+But "cache only entity keys" is not the end of it: some entities **copy fields from other entities**, which would bring the reverse-lookup problem back. The next section works out which entities are actually safe to cache.
+
+---
+
+## Which Entities to Cache
+
+Dropping relations leaves the entity keys. But not every entity key is truly one-to-one. Some entities store fields **copied from other entities**, and those copies go stale when the other entity changes — which brings back the same reverse lookup we just removed. So we look at what each cached entity actually holds.
+
+**Self-contained vs. derived.**
+
+| Entity | Copies a field from another entity? | Safe to cache on its own? |
+| ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
+| metalake, catalog, schema, table, topic, view, fileset | no — holds only its own data (columns, properties, comment…) | yes |
+| model, model version, function | no — but each holds a load-bearing pointer (the model version URI / latest version, or the function implementation) that goes stale on other nodes | no — left out for cross-node safety, see [Consistency](#consistency) |
+| tag, policy | no — associations are relations, not stored on the entity | yes |
+| user, group | yes — `roleNames` / `roleIds`, built from the user's roles | no |
+| role | yes — `securableObjects`, built from metadata objects | no |
+
+**Why user / group / role are a problem.**
+
+- `getUserByIdentifier` builds `roleNames` at read time by joining the user's roles (`UserMetaService` calls `RoleMetaService.listRolesByUserId`). If a role is dropped, it disappears from every user's list, but the user rows are not touched — so a cached user still lists the dropped role. Finding which users hold a role is a reverse lookup (role → users), exactly what dropping relations was meant to avoid.
+- `RoleEntity.securableObjects` has the same shape one level up: if a metadata object is renamed or dropped, a cached role that points at it is stale, and finding which roles point at an object is again a reverse lookup (object → roles).
+
+**Does authorization need these in the cache?** This is the key question, because authorization is the hot path. We checked `JcasbinAuthorizer`:
+
+- **user / group — no.** It reads user and group data through its own mappers (`UserMetaMapper`, `GroupMetaMapper`) into its own caches (`userRoleCache`, `groupRoleCache`), never through the entity store cache. So excluding user/group from the entity store cache does not affect authorization at all.
+- **role — only at cold start or after a change.** It does read role entities through the entity store (`entityStore.batchGet/get(ROLE)`), but only to (re)load a role's policies into the enforcer. Loaded roles are held in `loadedRoles`, a cache with `expireAfterAccess` (default 1 hour), so a role used at least once an hour never expires and the entity read is skipped. The entity read happens only on cold start, right after a role is edited, or after a role sits unused for over an hour — each a cheap one-time `batchGet`, not a per-request cost.
+
+So caching user, group, and role buys almost nothing (authorization does not depend on it) and costs a lot (the reverse-lookup problem comes back). tag and policy are safe to cache, but they are low-volume governance objects, not the read-heavy metadata the cache exists for.
+
+**Conclusion: cache only the basic metadata objects** — metalake, catalog, schema, table, topic, view, fileset. In code this is a small allowlist of entity types in the cache. Model, model version, and function are left out on purpose: they are read rarely, and each one holds a load-bearing pointer (the model version URI or latest version, or the function implementation) that would return a wrong answer on another node if it went stale — the per-alter check under [Consistency](#consistency) explains why. Every cached entity is then self-contained and one-to-one, so cross-node invalidation stays precise with no reverse lookups. As a bonus, these entities already write ALTER/DROP rows to `entity_change_log`, so the writer side needs no change at all.
+
+The cache now holds only self-contained metadata objects. The next question is how to tell the other nodes to drop a key when it changes.
+
+---
+
+## Approaches to Multi-Node Consistency
+
+Keeping a per-node cache fresh across a cluster is a common problem: after a write on one node, no other node may serve stale data. The standard techniques:
+
+| Approach | How it works | Trade-off |
+| -------------------------- | ------------------------------------------------------------------------------------------- |------------------------------------------------------------------------------------|
+| TTL only | each entry expires after a fixed time | no work, but every node serves old data until the TTL passes |
+| Pub/sub broadcast | the writer sends "invalidate X"; every node subscribes | low delay, but needs a message bus and must handle missed messages |
+| Change-log table + poller | the writer records the change in a DB table in the same transaction; each node polls it | no new infrastructure (reuses the DB), survives restarts; up to one poll of delay |
+| Shared (distributed) cache | one copy for the whole cluster, so there is nothing per-node to keep fresh | no propagation at all, but needs Redis/Memcached and a network round-trip per read |
+
+### How other metadata systems solve it
+
+We looked at how similar systems keep **their own per-node cache** coherent across a cluster (not how they notify downstream/derived systems — that is a different problem). **The most common answer is a per-node cache kept fresh by polling or by an invalidation/broadcast signal; no one relies on plain TTL.** Each row below has a source:
+
+| System | How it keeps its per-node cache fresh across nodes | Technique |
+| ---------------------------------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------|
+| **Hive Metastore** (`CachedStore`) | each node's in-memory cache is updated by a background thread that **polls the `NOTIFICATION_LOG` table** (written by `DbNotificationListener`); the log is in commit order and is the source of truth, and reads fall back to the DB until the thread catches up [1][2] | change-log + poll |
+| **Apache Ranger** (plugins) | each plugin keeps a **local policy cache** and **periodically polls Ranger Admin** for a newer version (default every 30s, `policy.pollIntervalMs`), downloading only the delta when the version changes [3] | periodic poll |
+| **Confluent Schema Registry** | one compacted Kafka topic **`_schemas`** is the commit log and the source of truth; every node reads it in a background thread to build its **local materialized view** [4] | shared log |
+| **Apache Impala** (`catalogd`) | metadata changes are **broadcast to all coordinators through `statestored`**; in local-catalog mode coordinators instead **fetch on demand and cache locally**, and invalidate that cache on `catalogd` failover [5] | broadcast / on-demand pull |
+| **Redis** (client-side caching) | with `CLIENT TRACKING` the server remembers which keys each client cached and **pushes an invalidation message** (RESP3 push) when a key changes, so the client flushes its local copy [6] | server-push invalidation |
+| **CockroachDB** | each node caches table/schema descriptors under a **versioned lease**; at most the **two latest versions** can be leased at once, and a schema change waits for old leases to be released or to expire (lease duration on the order of minutes) before advancing [7] | versioned lease |
+| **Trino** (Hive connector) | a coordinator-side metastore cache with a fixed **TTL plus background refresh** (`hive.metastore-cache-ttl`, `hive.metastore-refresh-interval`); its own docs note this can return stale data [8] | TTL + refresh |
+
+Two things stand out: **polling a change/version log (Hive, Ranger) is the most common, no-new-infrastructure answer**, and the one system that relies on **TTL alone (Trino) is documented to sometimes return stale data** — even CockroachDB, which looks TTL-like, actually uses bounded leases with active release, not plain expiry. That is exactly why TTL is not enough for us.
+
+### The two approaches we pick
+
+The closest match to what Gravitino needs is **Hive Metastore's `CachedStore`**: a per-node cache kept fresh by polling a change log in the same DB. Gravitino already has both pieces — the DB as the source of truth, and an `entity_change_log` table with a poller (built for the jcasbin cache). So this works with **no new infrastructure**. This is the default, and we call it `caffeine`.
+
+The broadcast / pub-sub-invalidation systems (Impala's `statestored`, Redis client-side caching, Schema Registry's shared log) work well, but they need a **message bus that Gravitino does not have**, so pub/sub is left for later (see the [roadmap](#roadmap)). **TTL alone** (Trino) is rejected for the stale-read reason its own docs give. That leaves two approaches that need no new component:
+
+- **reuse the DB** — a per-node cache kept fresh by the change log. → `caffeine`
+- **use a shared copy** — for teams already running Redis and wanting strong consistency, keep one copy in Redis. → `redis`
+
+**Sources**
+
+1. Hive — *Synchronized Metastore Cache*: <https://cwiki.apache.org/confluence/display/Hive/Synchronized+Metastore+Cache> (and HIVE-18661: <https://issues.apache.org/jira/browse/HIVE-18661>)
+2. Hive — `CachedStore.java` / `DbNotificationListener.java`: <https://github.com/apache/hive/blob/master/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/cache/CachedStore.java>
+3. Apache Ranger — *FAQ* (plugins cache policies locally and poll Ranger Admin at intervals): <https://ranger.apache.org/faq.html>; default `pollIntervalMs = 30000` in the plugin config: <https://github.com/apache/ranger/blob/master/hive-agent/conf/ranger-hive-security.xml>
+4. Confluent Schema Registry docs: <https://docs.confluent.io/platform/current/schema-registry/index.html>
+5. Apache Impala — *Metadata Management* (catalogd broadcasts via statestored; local-catalog mode fetches on demand and caches): <https://impala.apache.org/docs/build/html/topics/impala_metadata.html>
+6. Redis — *Client-side caching* / `CLIENT TRACKING` (RESP3 push invalidation): <https://redis.io/docs/latest/develop/reference/client-side-caching/>
+7. CockroachDB — *Table Descriptor Lease* RFC (at most two leased versions; ~5m lease): <https://github.com/cockroachdb/cockroach/blob/master/docs/RFCS/20151009_table_descriptor_lease.md> (and *Online Schema Changes*: <https://www.cockroachlabs.com/docs/stable/online-schema-changes>)
+8. Trino — *Metastores* docs: <https://trino.io/docs/current/object-storage/metastores.html> (stale-read note: <https://github.com/trinodb/trino/issues/10512>)
+
+---
+
+## The Pluggable Framework
+
+We now have two approaches that behave differently — one keeps a local copy per node, the other keeps one shared copy. To let a user pick either one by config, the cache stays **pluggable**, and each implementation says which kind it is. The `EntityCache` SPI adds one method:
+
+```
+EntityCache.coherence() → LOCAL_PER_NODE | SHARED
+```
+
+- `LOCAL_PER_NODE` — each node has its own copy, so a write must be **sent to the other nodes** to clear their copies. `caffeine` is this kind.
+- `SHARED` — one copy for the whole cluster, so a write clears it once and every node sees it. Nothing to send. `redis` is this kind.
+
+The write path is the same for both; only what happens after the local clear differs, and that is decided by `coherence()`:
+
+<!-- diagram source: diagrams/coherence-gate.mmd (regenerate with mermaid-cli) -->
+
+
+`CacheFactory.ENTITY_CACHES` is already a name → class table loaded by reflection, so adding `redis` next to `caffeine` is one new table entry with no change to the callers.
+
+The rest of this document describes each implementation — first the default local cache, then the shared cache.
+
+---
+
+# Implementation A — Caffeine (`caffeine`, `LOCAL_PER_NODE`, default)
+
+With only self-contained metadata objects cached, "entity X changed" names exactly the key to drop, and **any node can drop it** — no reverse key, no fan-out. The channel to carry "entity X changed" to the other nodes already exists and is already used by other caches.
+
+<!-- diagram source: diagrams/entity-key-invalidation.mmd (regenerate with mermaid-cli) -->
+
+
+### Reuse the existing transport
+
+`entity_change_log` and `EntityChangeLogPoller` already exist and are already used by two consumers:
+
+- `CatalogChangeLogListener` → clears `CatalogManager`'s catalog cache;
+- `JcasbinChangeListener` → clears jcasbin's **id-mapping cache** (`metadataIdCache`).
+
+Each row is `{metalake, entity_type, full_name, operate_type (ALTER | DROP), created_at}`. The structural MetaServices (metalake, catalog, schema, table, topic, view, fileset) already write a row on ALTER/DROP. We add the entity store cache as a **third consumer** of the same poller.
+
+### Writer side
+
+The cache now holds only metadata objects, and those **already write** an ALTER/DROP row to `entity_change_log` today. So the writer side needs **no change** — no new rows, no new columns, no new operate type:
+
+| Change | Cached? | Writes a change-log row |
+| ----------------------------------------------------- | ------- | ----------------------- |
+| structural ALTER/DROP (table, schema, catalog, …) | yes | yes — already emitted |
+| user / group / role / tag / policy ALTER/DROP | no | not needed (not cached) |
+| model / model version / function ALTER/DROP | no | not needed (not cached) |
+| relation change (grant, set owner, attach tag/policy) | no | not needed (not cached) |
+
+The existing structural rows are written in the same transaction as the entity write, so nothing new is added here.
+
+### Reader side
+
+A new `EntityChangeLogListener` for the entity store cache runs on the **same poller** and replays each row as a direct invalidation:
+
+```
+onEntityChange(rows):
+ for row in rows:
+ cache.invalidate(identOf(row), row.entity_type) # drop exactly this entity key
+```
+
+Dropping a container (for example a schema) must also drop its cached children. That uses the **forward** prefix scan the cache already has (`cacheIndex`), on the local node — the reverse index is not involved. This is the only remaining cascade.
+
+### A third consumer of the existing feed
+
+The entity store cache becomes a third consumer of the poller, next to the catalog cache and the jcasbin id-mapping cache. All three read the same structural ALTER/DROP rows that already exist — the entity store cache clears its entity key, the catalog cache clears its catalog, jcasbin clears its id mapping. There is no new row type, so the existing consumers do not change.
+
+### Consistency
+
+The cache never holds the truth. Every write goes to the DB first, under the version lock, so a stale cache can **never** cause a lost update or a bad write. The only thing that can go wrong is that a read on **another node** returns an old value for a short time — at most one poll interval, until that node drops the key.
+
+So the real question is simple: when another node reads an old value, does it matter? We went through every alter and every drop, for every cached entity, one at a time. A stale read falls into one of two buckets:
+
+- **The old value makes the next step fail with an error.** The user sees the error and tries again. This is safe.
+- **The old value is used silently and gives a wrong answer, with no error.** This is the dangerous kind.
+
+We only need to worry about the second bucket.
+
+#### Two groups of cached entities
+
+The danger depends on where the real data comes from.
+
+**Group 1 — the data comes from the connector: table, view, topic, and schemas in external catalogs.** For these, Gravitino does not read the metadata from its own cache. On every load it asks the underlying system (Hive, Iceberg, JDBC, Kafka) for the current object, and uses the cached entity only for Gravitino's own id and audit fields. All nodes ask the same underlying system, so they all see the same thing. If the object was dropped or renamed, the connector call fails right away with a "not found" error. **This whole group is safe — nothing to do.**
+
+**Group 2 — the data comes from Gravitino's own store: metalake, catalog, managed schema, fileset, model, model version, function.** Here the cached entity *is* the answer, so a stale read really can return an old value. We looked at each alter in this group.
+
+(Views follow the same rule as tables: their definition is read through the connector on every load, so they sit in Group 1 and are safe.)
+
+#### Walking through the alters in Group 2
+
+Most alters are safe:
+
+| Change | What a stale read does | Safe? |
+| -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
+| rename (metalake, catalog, schema, fileset, model) | reading the old name returns a leftover copy, but any write to it goes to the DB and fails; the new name misses the cache and loads fresh from the DB | yes |
+| update comment | you see an old comment for a moment | yes |
+| set / remove property (metalake, model, fileset) | these properties do not change where the data lives | yes |
+| fileset storage location | **cannot be changed** — there is no alter for it, so it can never go stale | yes |
+| drop | for Group 1 the connector call fails; for a fileset the file path is gone and access fails | yes |
+| catalog changes | already handled today by a separate cross-node signal (`CatalogChangeLogListener`), not by this cache | yes |
+
+Five cases are **not** safe — a stale read gives a wrong answer with no error. They are in the model area, functions, or the metalake on/off flag:
+
+| Change | Why a stale read is wrong, with no error |
+| --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| model version — update / add / remove URI | the URI points to the model files. An old URI silently loads the **wrong model files**. |
+| model version — update aliases | an alias silently points to the **wrong version**. |
+| model — latest version (after a new version is added on another node) | "get the latest version" silently returns an **old version**. |
+| function — add / update / remove implementation or definition | the implementation is the code the function runs. An old copy silently runs the **wrong function code**. |
+| metalake — disable | a node with a stale copy still thinks the metalake is on and **lets operations run** on a metalake that was turned off. (Turning it back on is safe: a stale node only throws "in use" by mistake.) |
+
+#### What we do about it
+
+We keep the simple design and remove the danger at the source:
+
+- **Do not cache the model area (model, model version) or functions.** The cache exists for the read-heavy path, which today is tables; model and function reads are a small share of traffic, so reading them from the DB every time costs almost nothing. Leaving these areas out removes four of the five dangerous cases outright and keeps the rule simple (an entity type is either in or out — no half-cached entity with a version-checked pointer). These reads are then always fresh, on every node. If model or function traffic grows later, we can add them back with a proper freshness check.
Review Comment:
OK, then we should define an explicit scope in the code to let developers know that what is cached and what is not. Besides, we should document it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#issuecomment-5021036877
What is the status for now?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3595556864
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -225,16 +225,17 @@ Each row is `{metalake, entity_type, full_name, operate_type (ALTER | DROP), cre
### Writer side
-The cache now holds only metadata objects, and those **already write** an ALTER/DROP row to `entity_change_log` today. So the writer side needs **no change** — no new rows, no new columns, no new operate type:
+Most cached objects **already write** an ALTER/DROP row to `entity_change_log` today, so the writer side is almost unchanged — no new columns and no new operate type. The one addition is a change-log row for **tag and policy**, which are cached but do not emit one yet:
-| Change | Cached? | Writes a change-log row |
-| ----------------------------------------------------- | ------- | ----------------------- |
-| structural ALTER/DROP (table, schema, catalog, …) | yes | yes — already emitted |
-| user / group / role / tag / policy ALTER/DROP | no | not needed (not cached) |
-| model / model version / function ALTER/DROP | no | not needed (not cached) |
-| relation change (grant, set owner, attach tag/policy) | no | not needed (not cached) |
+| Change | Cached? | Writes a change-log row |
+| ----------------------------------------------------- | ------- | ------------------------------------- |
+| structural ALTER/DROP (table, schema, catalog, …) | yes | yes — already emitted |
+| tag / policy ALTER/DROP | yes | **add a new emit point** (none today) |
+| user / group / role ALTER/DROP | no | not needed (not cached) |
+| model / model version / function ALTER/DROP | no | not needed (not cached) |
+| relation change (grant, set owner, attach tag/policy) | no | not needed (not cached) |
-The existing structural rows are written in the same transaction as the entity write, so nothing new is added here.
+The existing structural rows are written in the same transaction as the entity write; the new tag/policy rows must be written the same way, in the same transaction as the tag/policy write.
Review Comment:
Thinking a bit.
The principal that the entity store cache will only handle single entities remains unchanged. If the performance of tag relations is poor during authorization, I will cooperate with the guy who is responsible for tag-based access control to optimize it. Entity store cache will only be used in basic API operations like load/alter/list tags.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3557571927
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -252,10 +252,55 @@ The entity store cache becomes a third consumer of the poller, next to the catal
### Consistency
+The cache is never the source of truth. The write path always reads the DB under the optimistic version lock, so eventual consistency can **never** cause a lost update or corrupt data. Its only observable effect is **bounded read staleness on non-writing nodes**: for up to one poll interval, a node other than the writer may serve an older value.
+
- **Other nodes:** eventual — an entity key is dropped within one poll interval of the change.
- **Writing node:** unchanged — it still clears its own cache on the write path, so it reads its own writes right away. Its own row is replayed later, which does nothing (clearing an already-clear key is a no-op).
- **Write path:** unchanged — it reads the DB with the optimistic version check.
+The rest of this section works through every way that staleness window can be observed, and how each is handled.
+
+#### Staleness scenarios and mitigations
+
+**1. Plain stale read (bounded, mostly tolerable).**
+
+| # | Scenario | Effect | Possible mitigation |
+| - | -------------------------------------------------------------- |-----------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------|
+| 1 | Node A ALTERs a table (add column); B GETs it | B serves the old schema for up to one poll interval | Accept within the SLA window; a caller that needs an exact schema uses a consistent (cache-bypass) read |
+| 2 | Node A DROPs a table; B GETs it | B still reports it as present (cache hit) until the next poll | Accept — any write to it on B is re-validated against the DB and rejected as not-found, so no corruption |
+| 3 | RENAME (the old name behaves like a DROP); B GETs the old name | B keeps resolving the old name until the next poll; the new name misses → DB load | Same as DROP — bounded by the poll interval |
+| 4 | A property changes (e.g. Iceberg metadata-location); B GETs it | B returns the old location → a query on B may read an old snapshot/path | Highest-value case: offer a consistent (cache-bypass) read for location-sensitive callers, or use `redis` |
Review Comment:
Okay, I will check it on a case-by-case basis.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3584811169
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -252,54 +254,68 @@ The entity store cache becomes a third consumer of the poller, next to the catal
### Consistency
-The cache is never the source of truth. The write path always reads the DB under the optimistic version lock, so eventual consistency can **never** cause a lost update or corrupt data. Its only observable effect is **bounded read staleness on non-writing nodes**: for up to one poll interval, a node other than the writer may serve an older value.
+The cache never holds the truth. Every write goes to the DB first, under the version lock, so a stale cache can **never** cause a lost update or a bad write. The only thing that can go wrong is that a read on **another node** returns an old value for a short time — at most one poll interval, until that node drops the key.
-- **Other nodes:** eventual — an entity key is dropped within one poll interval of the change.
-- **Writing node:** unchanged — it still clears its own cache on the write path, so it reads its own writes right away. Its own row is replayed later, which does nothing (clearing an already-clear key is a no-op).
-- **Write path:** unchanged — it reads the DB with the optimistic version check.
+So the real question is simple: when another node reads an old value, does it matter? We went through every alter and every drop, for every cached entity, one at a time. A stale read falls into one of two buckets:
-The rest of this section works through every way that staleness window can be observed, and how each is handled.
+- **The old value makes the next step fail with an error.** The user sees the error and tries again. This is safe.
+- **The old value is used silently and gives a wrong answer, with no error.** This is the dangerous kind.
-#### Staleness scenarios and mitigations
+We only need to worry about the second bucket.
-**1. Plain stale read (bounded, mostly tolerable).**
+#### Two groups of cached entities
-| # | Scenario | Effect | Possible mitigation |
-| - | -------------------------------------------------------------- |-----------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------|
-| 1 | Node A ALTERs a table (add column); B GETs it | B serves the old schema for up to one poll interval | Accept within the SLA window; a caller that needs an exact schema uses a consistent (cache-bypass) read |
-| 2 | Node A DROPs a table; B GETs it | B still reports it as present (cache hit) until the next poll | Accept — any write to it on B is re-validated against the DB and rejected as not-found, so no corruption |
-| 3 | RENAME (the old name behaves like a DROP); B GETs the old name | B keeps resolving the old name until the next poll; the new name misses → DB load | Same as DROP — bounded by the poll interval |
-| 4 | A property changes (e.g. Iceberg metadata-location); B GETs it | B returns the old location → a query on B may read an old snapshot/path | Highest-value case: offer a consistent (cache-bypass) read for location-sensitive callers, or use `redis` |
+The danger depends on where the real data comes from.
-**2. Read-your-writes across nodes.**
+**Group 1 — the data comes from the connector: table, view, topic, and schemas in external catalogs.** For these, Gravitino does not read the metadata from its own cache. On every load it asks the underlying system (Hive, Iceberg, JDBC, Kafka) for the current object, and uses the cached entity only for Gravitino's own id and audit fields. All nodes ask the same underlying system, so they all see the same thing. If the object was dropped or renamed, the connector call fails right away with a "not found" error. **This whole group is safe — nothing to do.**
-| # | Scenario | Effect | Possible mitigation |
-| - |---------------------------------------------------------------------|-------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
-| 5 | Through a load balancer, ALTER on A then an immediate read on B | Stale — violates session consistency; without sticky routing the change looks lost | Sticky sessions at the LB, or a client-supplied last-seen version that bypasses the cache when the copy is older; `redis` removes it entirely |
-| 6 | CREATE (rather than ALTER/DROP) | No problem — no negative caching and `list` skips the cache, so a new entity is visible at once | None needed |
+**Group 2 — the data comes from Gravitino's own store: metalake, catalog, managed schema, fileset, model, model version, function.** Here the cached entity *is* the answer, so a stale read really can return an old value. We looked at each alter in this group.
-**3. Cross-node read-modify-write.**
+(Views follow the same rule as tables: their definition is read through the connector on every load, so they sit in Group 1 and are safe.)
-| # | Scenario | Effect | Possible mitigation |
-| - | ------------------------------------------------------------------------------------- |-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------|
-| 7 | B reads stale value A and submits an update carrying A's version as the expected one | The optimistic lock rejects it on version mismatch — safe, but the user sees an unexpected conflict | Accept (correctness is preserved); reduce its frequency with the read-your-writes mitigations above |
+#### Walking through the alters in Group 2
-**4. Is the window actually bounded? — poller reliability (the real risk).** The "at most one poll interval" guarantee holds **only if the poller never drops a row**. If it does, the stale entry survives until the cache TTL, so this is the one place eventual consistency itself can break.
+Most alters are safe:
-| # | Scenario | Effect | Possible mitigation |
-| -- |-----------------------------------------------------------------------------------------------------------|-----------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------|
-| 8 | Commit-ordering gap / a skipped row | The key is never invalidated; stale until the TTL | Reuse the lag-safe, id-based polling already built for the change log (`#11736`); keep the cache TTL as a backstop |
-| 9 | Poller thread dies / DB briefly unreachable | That node serves stale data until the TTL | TTL backstop + monitor poller liveness/lag and alert |
-| 10 | Hierarchical DROP: only the container (schema) emits a row; children are cleared by a forward prefix scan | Correct as long as the prefix scan covers every child key | Cover with the hierarchical-drop test; confirm no child is written in a separate transaction that outlives the container row |
+| Change | What a stale read does | Safe? |
+| -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
+| rename (metalake, catalog, schema, fileset, model) | reading the old name returns a leftover copy, but any write to it goes to the DB and fails; the new name misses the cache and loads fresh from the DB | yes |
+| update comment | you see an old comment for a moment | yes |
+| set / remove property (metalake, model, fileset) | these properties do not change where the data lives | yes |
+| fileset storage location | **cannot be changed** — there is no alter for it, so it can never go stale | yes |
+| drop | for Group 1 the connector call fails; for a fileset the file path is gone and access fails | yes |
+| catalog changes | already handled today by a separate cross-node signal (`CatalogChangeLogListener`), not by this cache | yes |
-**5. Idempotency (no issue).** Replaying ALTER then DROP, in any order or duplicated, is safe: invalidation is idempotent, so out-of-order or repeated replay has no effect.
+Five cases are **not** safe — a stale read gives a wrong answer with no error. They are in the model area, functions, or the metalake on/off flag:
-#### Summary: main risks, resolutions, and the staleness SLA
+| Change | Why a stale read is wrong, with no error |
+| --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| model version — update / add / remove URI | the URI points to the model files. An old URI silently loads the **wrong model files**. |
+| model version — update aliases | an alias silently points to the **wrong version**. |
+| model — latest version (after a new version is added on another node) | "get the latest version" silently returns an **old version**. |
+| function — add / update / remove implementation or definition | the implementation is the code the function runs. An old copy silently runs the **wrong function code**. |
+| metalake — disable | a node with a stale copy still thinks the metalake is on and **lets operations run** on a metalake that was turned off. (Turning it back on is safe: a stale node only throws "in use" by mistake.) |
Review Comment:
How about others like tag, policy?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3543977997
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -0,0 +1,350 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+---
+title: "Multi-Node Support for the Entity Store Cache"
+status: "Draft"
+date: "2026-07-07"
+---
+
+## Background
+
+Gravitino has two caches:
+
+- The **jcasbin authorization cache** already works with more than one node.
+- The **entity store cache** does not. When a change happens on node A, only node A clears its cache. Node B keeps serving the old data until its entry expires.
+
+Because of this, the only safe way to run more than one node today is to turn the entity store cache off (`gravitino.cache.enabled=false`). That is bad for read-heavy catalogs, especially Iceberg.
+
+This document proposes a design to make the entity store cache correct when running more than one node. It is a design proposal; no behavior has changed yet.
+
+## Goals and Non-Goals
+
+**Goals**
+
+- Make the entity store cache correct with more than one node, so `gravitino.cache.enabled=true` is safe.
+- Keep the cache **pluggable**: one SPI, chosen by `gravitino.cache.impl`. Ship `caffeine` as the default (no extra dependency) and `redis` as an option the user turns on by config.
+- Keep single-node behavior and the write path (the optimistic version lock) unchanged.
+
+**Non-Goals**
+
+- Replace the entity store or its write path. The cache sits in front of the store and is never the source of truth.
+- Add a cluster membership / gossip layer or any other complex distributed system. We only use the DB Gravitino already needs, or the external cache the user turns on.
+
+---
+
+## Current Cache Implementation
+
+`EntityCache` is already an SPI, chosen by `gravitino.cache.impl` and created by `CacheFactory`. There is one implementation today, `CaffeineEntityCache` (`caffeine`): an in-memory cache, **one copy per node**, with two kinds of entries:
+
+- **entity keys** `(ident, type)` → the entity itself;
+- **relation keys** `(ident, type, relType)` → the list of related entities, stored **in both directions** and kept in step by an in-process **reverse index** (`ReverseIndexCache`).
+
+On a write, the node clears the changed key and then uses the reverse index to clear the related keys. On a single node this is correct. The problem is that this clearing happens **only on the node that made the change** (`RelationalEntityStore` calls `cache.invalidate(...)` locally). Nothing tells the other nodes, so they serve old data until their entries expire.
+
+Some behavior is already safe with more than one node and does not change:
+
+| Already correct | Why |
+| ------------------------- | ---------------------------------------------------------------------------- |
+| Writes never lose updates | The write path reads the DB (not the cache) with an optimistic version check |
+| `list(namespace)` | Skips the cache, so it is never stale |
+| CREATE | Needs nothing: no negative caching, and `list` skips the cache |
+
+The rest of the problem splits in two:
+
+- **entity keys** are one-to-one. "table T changed" names exactly the key to drop, and any node can drop it. This is easy.
+- **relation keys** have a reverse key. Dropping one side (say a role) also means dropping the other side's key (each user that had the role), but "the role changed" does not say *which* users those are. The writing node knows them from its local reverse index; a remote node may not.
+
+That reverse key is the hard part. So the first question is whether the cache needs relations at all.
+
+---
+
+## Do We Need to Cache Relations?
+
+All the cross-node difficulty comes from relation caching (the reverse key and the write fan-out). Before building around it, we checked whether it is actually important for performance. It is not.
+
+**Who reads the relation cache.** The cached relation path is `RelationalEntityStore.listEntitiesByRelation`, which runs **one indexed SQL join** per call (`JDBCBackend.listEntitiesByRelation`). Its callers are all metadata governance managers:
+
+| Caller | Relation | API that uses it |
+| -------------------- | ---------------------------- |-----------------------------------|
+| `OwnerManager` | `OWNER_REL` | `GET .../owner` |
+| `RoleManager` | role relations | role / authorization management |
+| `FutureGrantManager` | role/user/group relations | applying future grants (admin op) |
+| `TagManager` | `TAG_METADATA_OBJECT_REL` | tag endpoints |
+| `PolicyManager` | `POLICY_METADATA_OBJECT_REL` | policy endpoints |
+
+**Who does not.** The two paths that must be fast do **not** use it:
+
+- **Core metadata reads** (`get` / `list` of table, schema, catalog, …) never call `listEntitiesByRelation`. Removing the relation cache does not affect them at all.
+- **Authorization checks** (`JcasbinAuthorizer`) read roles straight from mappers (`RoleMetaMapper.listRolesByUserId` / `listRolesByGroupId`), owner from its own `ownerRelCache` (which polls `owner_meta`), and id from its own `metadataIdCache`. It does not use the entity store relation cache at all. Relation caching was first added with authorization in mind, but authorization no longer uses it.
+
+**Cost of removing it.** Each call becomes one indexed query — not an N+1 (one query per item). No list endpoint loads relations per item in a loop. The one place a single request makes several queries is **tag / policy inheritance**: listing an object's tags also reads its parents (the object plus up to ~3 ancestors), so a tag lookup is up to ~4 single-row queries; the cache mainly saves re-reading popular parents. This is the only workload where removing the cache adds real DB load, and it can be measured today — those calls are already `@Monitored` (`baseMetricName = "listTagsForMetadataObject"`, `"getOwner"`, `"listPoliciesForMetadataObject"`).
Review Comment:
Let me analyze optimize it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3544046007
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -0,0 +1,350 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+---
+title: "Multi-Node Support for the Entity Store Cache"
+status: "Draft"
+date: "2026-07-07"
+---
+
+## Background
+
+Gravitino has two caches:
+
+- The **jcasbin authorization cache** already works with more than one node.
+- The **entity store cache** does not. When a change happens on node A, only node A clears its cache. Node B keeps serving the old data until its entry expires.
+
+Because of this, the only safe way to run more than one node today is to turn the entity store cache off (`gravitino.cache.enabled=false`). That is bad for read-heavy catalogs, especially Iceberg.
+
+This document proposes a design to make the entity store cache correct when running more than one node. It is a design proposal; no behavior has changed yet.
+
+## Goals and Non-Goals
+
+**Goals**
+
+- Make the entity store cache correct with more than one node, so `gravitino.cache.enabled=true` is safe.
+- Keep the cache **pluggable**: one SPI, chosen by `gravitino.cache.impl`. Ship `caffeine` as the default (no extra dependency) and `redis` as an option the user turns on by config.
+- Keep single-node behavior and the write path (the optimistic version lock) unchanged.
+
+**Non-Goals**
+
+- Replace the entity store or its write path. The cache sits in front of the store and is never the source of truth.
+- Add a cluster membership / gossip layer or any other complex distributed system. We only use the DB Gravitino already needs, or the external cache the user turns on.
+
+---
+
+## Current Cache Implementation
+
+`EntityCache` is already an SPI, chosen by `gravitino.cache.impl` and created by `CacheFactory`. There is one implementation today, `CaffeineEntityCache` (`caffeine`): an in-memory cache, **one copy per node**, with two kinds of entries:
+
+- **entity keys** `(ident, type)` → the entity itself;
+- **relation keys** `(ident, type, relType)` → the list of related entities, stored **in both directions** and kept in step by an in-process **reverse index** (`ReverseIndexCache`).
+
+On a write, the node clears the changed key and then uses the reverse index to clear the related keys. On a single node this is correct. The problem is that this clearing happens **only on the node that made the change** (`RelationalEntityStore` calls `cache.invalidate(...)` locally). Nothing tells the other nodes, so they serve old data until their entries expire.
+
+Some behavior is already safe with more than one node and does not change:
+
+| Already correct | Why |
+| ------------------------- | ---------------------------------------------------------------------------- |
+| Writes never lose updates | The write path reads the DB (not the cache) with an optimistic version check |
+| `list(namespace)` | Skips the cache, so it is never stale |
+| CREATE | Needs nothing: no negative caching, and `list` skips the cache |
+
+The rest of the problem splits in two:
+
+- **entity keys** are one-to-one. "table T changed" names exactly the key to drop, and any node can drop it. This is easy.
+- **relation keys** have a reverse key. Dropping one side (say a role) also means dropping the other side's key (each user that had the role), but "the role changed" does not say *which* users those are. The writing node knows them from its local reverse index; a remote node may not.
+
+That reverse key is the hard part. So the first question is whether the cache needs relations at all.
+
+---
+
+## Do We Need to Cache Relations?
+
+All the cross-node difficulty comes from relation caching (the reverse key and the write fan-out). Before building around it, we checked whether it is actually important for performance. It is not.
+
+**Who reads the relation cache.** The cached relation path is `RelationalEntityStore.listEntitiesByRelation`, which runs **one indexed SQL join** per call (`JDBCBackend.listEntitiesByRelation`). Its callers are all metadata governance managers:
+
+| Caller | Relation | API that uses it |
+| -------------------- | ---------------------------- |-----------------------------------|
+| `OwnerManager` | `OWNER_REL` | `GET .../owner` |
+| `RoleManager` | role relations | role / authorization management |
+| `FutureGrantManager` | role/user/group relations | applying future grants (admin op) |
+| `TagManager` | `TAG_METADATA_OBJECT_REL` | tag endpoints |
+| `PolicyManager` | `POLICY_METADATA_OBJECT_REL` | policy endpoints |
+
+**Who does not.** The two paths that must be fast do **not** use it:
+
+- **Core metadata reads** (`get` / `list` of table, schema, catalog, …) never call `listEntitiesByRelation`. Removing the relation cache does not affect them at all.
+- **Authorization checks** (`JcasbinAuthorizer`) read roles straight from mappers (`RoleMetaMapper.listRolesByUserId` / `listRolesByGroupId`), owner from its own `ownerRelCache` (which polls `owner_meta`), and id from its own `metadataIdCache`. It does not use the entity store relation cache at all. Relation caching was first added with authorization in mind, but authorization no longer uses it.
+
+**Cost of removing it.** Each call becomes one indexed query — not an N+1 (one query per item). No list endpoint loads relations per item in a loop. The one place a single request makes several queries is **tag / policy inheritance**: listing an object's tags also reads its parents (the object plus up to ~3 ancestors), so a tag lookup is up to ~4 single-row queries; the cache mainly saves re-reading popular parents. This is the only workload where removing the cache adds real DB load, and it can be measured today — those calls are already `@Monitored` (`baseMetricName = "listTagsForMetadataObject"`, `"getOwner"`, `"listPoliciesForMetadataObject"`).
+
+**Decision.** Remove relation caching from the entity store cache. Relation reads go straight to the DB (one indexed query each), the same as authorization already does. This is safe for the core read path and for authorization; the only risk is workloads with heavy tag/policy inheritance reads, which we can watch with the existing metrics and, if ever needed, address by adding precise relation caching back later.
+
+The result: the cache holds only **entity keys**, so cross-node invalidation becomes the easy one-to-one case, and (as both implementations show) each design loses its hardest part. The `ReverseIndexCache` and the two-direction relation keys are removed with it.
+
+But "cache only entity keys" is not the end of it: some entities **copy fields from other entities**, which would bring the reverse-lookup problem back. The next section works out which entities are actually safe to cache.
+
+---
+
+## Which Entities to Cache
+
+Dropping relations leaves the entity keys. But not every entity key is truly one-to-one. Some entities store fields **copied from other entities**, and those copies go stale when the other entity changes — which brings back the same reverse lookup we just removed. So we look at what each cached entity actually holds.
+
+**Self-contained vs. derived.**
+
+| Entity | Copies a field from another entity? | Safe to cache on its own? |
+| ------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------- |
+| metalake, catalog, schema, table, topic, model, view, fileset | no — holds only its own data (columns, properties, comment…) | yes |
+| tag, policy | no — associations are relations, not stored on the entity | yes |
+| user, group | yes — `roleNames` / `roleIds`, built from the user's roles | no |
+| role | yes — `securableObjects`, built from metadata objects | no |
+
+**Why user / group / role are a problem.**
+
+- `getUserByIdentifier` builds `roleNames` at read time by joining the user's roles (`UserMetaService` calls `RoleMetaService.listRolesByUserId`). If a role is dropped, it disappears from every user's list, but the user rows are not touched — so a cached user still lists the dropped role. Finding which users hold a role is a reverse lookup (role → users), exactly what dropping relations was meant to avoid.
+- `RoleEntity.securableObjects` has the same shape one level up: if a metadata object is renamed or dropped, a cached role that points at it is stale, and finding which roles point at an object is again a reverse lookup (object → roles).
+
+**Does authorization need these in the cache?** This is the key question, because authorization is the hot path. We checked `JcasbinAuthorizer`:
+
+- **user / group — no.** It reads user and group data through its own mappers (`UserMetaMapper`, `GroupMetaMapper`) into its own caches (`userRoleCache`, `groupRoleCache`), never through the entity store cache. So excluding user/group from the entity store cache does not affect authorization at all.
+- **role — only at cold start or after a change.** It does read role entities through the entity store (`entityStore.batchGet/get(ROLE)`), but only to (re)load a role's policies into the enforcer. Loaded roles are held in `loadedRoles`, a cache with `expireAfterAccess` (default 1 hour), so a role used at least once an hour never expires and the entity read is skipped. The entity read happens only on cold start, right after a role is edited, or after a role sits unused for over an hour — each a cheap one-time `batchGet`, not a per-request cost.
+
+So caching user, group, and role buys almost nothing (authorization does not depend on it) and costs a lot (the reverse-lookup problem comes back). tag and policy are safe to cache, but they are low-volume governance objects, not the read-heavy metadata the cache exists for.
+
+**Conclusion: cache only the basic metadata objects** — metalake, catalog, schema, table, topic, model, view, fileset. In code this is a small allowlist of entity types in the cache. Every cached entity is then self-contained and one-to-one, so cross-node invalidation stays precise with no reverse lookups. As a bonus, these entities already write ALTER/DROP rows to `entity_change_log`, so the writer side needs no change at all.
+
+The cache now holds only self-contained metadata objects. The next question is how to tell the other nodes to drop a key when it changes.
+
+---
+
+## Approaches to Multi-Node Consistency
+
+Keeping a per-node cache fresh across a cluster is a common problem: after a write on one node, no other node may serve stale data. The standard techniques:
+
+| Approach | How it works | Trade-off |
+| -------------------------- | ------------------------------------------------------------------------------------------- |------------------------------------------------------------------------------------|
+| TTL only | each entry expires after a fixed time | no work, but every node serves old data until the TTL passes |
+| Pub/sub broadcast | the writer sends "invalidate X"; every node subscribes | low delay, but needs a message bus and must handle missed messages |
+| Change-log table + poller | the writer records the change in a DB table in the same transaction; each node polls it | no new infrastructure (reuses the DB), survives restarts; up to one poll of delay |
+| Shared (distributed) cache | one copy for the whole cluster, so there is nothing per-node to keep fresh | no propagation at all, but needs Redis/Memcached and a network round-trip per read |
+
+### How other metadata systems solve it
+
+We looked at how similar systems keep **their own per-node cache** coherent across a cluster (not how they notify downstream/derived systems — that is a different problem). **The most common answer is a per-node cache kept fresh by polling or by an invalidation/broadcast signal; no one relies on plain TTL.** Each row below has a source:
+
+| System | How it keeps its per-node cache fresh across nodes | Technique |
+| ---------------------------------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------|
+| **Hive Metastore** (`CachedStore`) | each node's in-memory cache is updated by a background thread that **polls the `NOTIFICATION_LOG` table** (written by `DbNotificationListener`); the log is in commit order and is the source of truth, and reads fall back to the DB until the thread catches up [1][2] | change-log + poll |
+| **Apache Ranger** (plugins) | each plugin keeps a **local policy cache** and **periodically polls Ranger Admin** for a newer version (default every 30s, `policy.pollIntervalMs`), downloading only the delta when the version changes [3] | periodic poll |
+| **Confluent Schema Registry** | one compacted Kafka topic **`_schemas`** is the commit log and the source of truth; every node reads it in a background thread to build its **local materialized view** [4] | shared log |
+| **Apache Impala** (`catalogd`) | metadata changes are **broadcast to all coordinators through `statestored`**; in local-catalog mode coordinators instead **fetch on demand and cache locally**, and invalidate that cache on `catalogd` failover [5] | broadcast / on-demand pull |
+| **Redis** (client-side caching) | with `CLIENT TRACKING` the server remembers which keys each client cached and **pushes an invalidation message** (RESP3 push) when a key changes, so the client flushes its local copy [6] | server-push invalidation |
+| **CockroachDB** | each node caches table/schema descriptors under a **versioned lease**; at most the **two latest versions** can be leased at once, and a schema change waits for old leases to be released or to expire (lease duration on the order of minutes) before advancing [7] | versioned lease |
+| **Trino** (Hive connector) | a coordinator-side metastore cache with a fixed **TTL plus background refresh** (`hive.metastore-cache-ttl`, `hive.metastore-refresh-interval`); its own docs note this can return stale data [8] | TTL + refresh |
+
+Two things stand out: **polling a change/version log (Hive, Ranger) is the most common, no-new-infrastructure answer**, and the one system that relies on **TTL alone (Trino) is documented to sometimes return stale data** — even CockroachDB, which looks TTL-like, actually uses bounded leases with active release, not plain expiry. That is exactly why TTL is not enough for us.
+
+### The two approaches we pick
+
+The closest match to what Gravitino needs is **Hive Metastore's `CachedStore`**: a per-node cache kept fresh by polling a change log in the same DB. Gravitino already has both pieces — the DB as the source of truth, and an `entity_change_log` table with a poller (built for the jcasbin cache). So this works with **no new infrastructure**. This is the default, and we call it `caffeine`.
+
+The broadcast / pub-sub-invalidation systems (Impala's `statestored`, Redis client-side caching, Schema Registry's shared log) work well, but they need a **message bus that Gravitino does not have**, so pub/sub is left for later (see the [roadmap](#roadmap)). **TTL alone** (Trino) is rejected for the stale-read reason its own docs give. That leaves two approaches that need no new component:
+
+- **reuse the DB** — a per-node cache kept fresh by the change log. → `caffeine`
+- **use a shared copy** — for teams already running Redis and wanting strong consistency, keep one copy in Redis. → `redis`
+
+**Sources**
+
+1. Hive — *Synchronized Metastore Cache*: <https://cwiki.apache.org/confluence/display/Hive/Synchronized+Metastore+Cache> (and HIVE-18661: <https://issues.apache.org/jira/browse/HIVE-18661>)
+2. Hive — `CachedStore.java` / `DbNotificationListener.java`: <https://github.com/apache/hive/blob/master/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/cache/CachedStore.java>
+3. Apache Ranger — *FAQ* (plugins cache policies locally and poll Ranger Admin at intervals): <https://ranger.apache.org/faq.html>; default `pollIntervalMs = 30000` in the plugin config: <https://github.com/apache/ranger/blob/master/hive-agent/conf/ranger-hive-security.xml>
+4. Confluent Schema Registry docs: <https://docs.confluent.io/platform/current/schema-registry/index.html>
+5. Apache Impala — *Metadata Management* (catalogd broadcasts via statestored; local-catalog mode fetches on demand and caches): <https://impala.apache.org/docs/build/html/topics/impala_metadata.html>
+6. Redis — *Client-side caching* / `CLIENT TRACKING` (RESP3 push invalidation): <https://redis.io/docs/latest/develop/reference/client-side-caching/>
+7. CockroachDB — *Table Descriptor Lease* RFC (at most two leased versions; ~5m lease): <https://github.com/cockroachdb/cockroach/blob/master/docs/RFCS/20151009_table_descriptor_lease.md> (and *Online Schema Changes*: <https://www.cockroachlabs.com/docs/stable/online-schema-changes>)
+8. Trino — *Metastores* docs: <https://trino.io/docs/current/object-storage/metastores.html> (stale-read note: <https://github.com/trinodb/trino/issues/10512>)
+
+---
+
+## The Pluggable Framework
+
+We now have two approaches that behave differently — one keeps a local copy per node, the other keeps one shared copy. To let a user pick either one by config, the cache stays **pluggable**, and each implementation says which kind it is. The `EntityCache` SPI adds one method:
+
+```
+EntityCache.coherence() → LOCAL_PER_NODE | SHARED
+```
+
+- `LOCAL_PER_NODE` — each node has its own copy, so a write must be **sent to the other nodes** to clear their copies. `caffeine` is this kind.
+- `SHARED` — one copy for the whole cluster, so a write clears it once and every node sees it. Nothing to send. `redis` is this kind.
+
+The write path is the same for both; only what happens after the local clear differs, and that is decided by `coherence()`:
+
+<!-- diagram source: diagrams/coherence-gate.mmd (regenerate with mermaid-cli) -->
+
+
+`CacheFactory.ENTITY_CACHES` is already a name → class table loaded by reflection, so adding `redis` next to `caffeine` is one new table entry with no change to the callers.
+
+The rest of this document describes each implementation — first the default local cache, then the shared cache.
+
+---
+
+# Implementation A — Caffeine (`caffeine`, `LOCAL_PER_NODE`, default)
+
+With only self-contained metadata objects cached, "entity X changed" names exactly the key to drop, and **any node can drop it** — no reverse key, no fan-out. The channel to carry "entity X changed" to the other nodes already exists and is already used by other caches.
+
+<!-- diagram source: diagrams/entity-key-invalidation.mmd (regenerate with mermaid-cli) -->
+
+
+### Reuse the existing transport
+
+`entity_change_log` and `EntityChangeLogPoller` already exist and are already used by two consumers:
+
+- `CatalogChangeLogListener` → clears `CatalogManager`'s catalog cache;
+- `JcasbinChangeListener` → clears jcasbin's **id-mapping cache** (`metadataIdCache`).
+
+Each row is `{metalake, entity_type, full_name, operate_type (ALTER | DROP), created_at}`. The structural MetaServices (metalake, catalog, schema, table, topic, model, view, fileset) already write a row on ALTER/DROP. We add the entity store cache as a **third consumer** of the same poller.
+
+### Writer side
+
+The cache now holds only metadata objects, and those **already write** an ALTER/DROP row to `entity_change_log` today. So the writer side needs **no change** — no new rows, no new columns, no new operate type:
+
+| Change | Cached? | Writes a change-log row |
+| ----------------------------------------------------- | ------- | ----------------------- |
+| structural ALTER/DROP (table, schema, catalog, …) | yes | yes — already emitted |
+| user / group / role / tag / policy ALTER/DROP | no | not needed (not cached) |
+| relation change (grant, set owner, attach tag/policy) | no | not needed (not cached) |
+
+The existing structural rows are written in the same transaction as the entity write, so nothing new is added here.
+
+### Reader side
+
+A new `EntityChangeLogListener` for the entity store cache runs on the **same poller** and replays each row as a direct invalidation:
+
+```
+onEntityChange(rows):
+ for row in rows:
+ cache.invalidate(identOf(row), row.entity_type) # drop exactly this entity key
+```
+
+Dropping a container (for example a schema) must also drop its cached children. That uses the **forward** prefix scan the cache already has (`cacheIndex`), on the local node — the reverse index is not involved. This is the only remaining cascade.
Review Comment:
Yeah, using the change log can only achieve eventual consistency. The conventional way can only guarantee an eventual consistency model. If a strong model is required, then a shared cache like Redis should be used, or some ways like version check, but the benefit of version check is unclear, and in other ways is unworthy to some extent.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3584914131
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -252,54 +254,68 @@ The entity store cache becomes a third consumer of the poller, next to the catal
### Consistency
-The cache is never the source of truth. The write path always reads the DB under the optimistic version lock, so eventual consistency can **never** cause a lost update or corrupt data. Its only observable effect is **bounded read staleness on non-writing nodes**: for up to one poll interval, a node other than the writer may serve an older value.
+The cache never holds the truth. Every write goes to the DB first, under the version lock, so a stale cache can **never** cause a lost update or a bad write. The only thing that can go wrong is that a read on **another node** returns an old value for a short time — at most one poll interval, until that node drops the key.
-- **Other nodes:** eventual — an entity key is dropped within one poll interval of the change.
-- **Writing node:** unchanged — it still clears its own cache on the write path, so it reads its own writes right away. Its own row is replayed later, which does nothing (clearing an already-clear key is a no-op).
-- **Write path:** unchanged — it reads the DB with the optimistic version check.
+So the real question is simple: when another node reads an old value, does it matter? We went through every alter and every drop, for every cached entity, one at a time. A stale read falls into one of two buckets:
-The rest of this section works through every way that staleness window can be observed, and how each is handled.
+- **The old value makes the next step fail with an error.** The user sees the error and tries again. This is safe.
+- **The old value is used silently and gives a wrong answer, with no error.** This is the dangerous kind.
-#### Staleness scenarios and mitigations
+We only need to worry about the second bucket.
-**1. Plain stale read (bounded, mostly tolerable).**
+#### Two groups of cached entities
-| # | Scenario | Effect | Possible mitigation |
-| - | -------------------------------------------------------------- |-----------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------|
-| 1 | Node A ALTERs a table (add column); B GETs it | B serves the old schema for up to one poll interval | Accept within the SLA window; a caller that needs an exact schema uses a consistent (cache-bypass) read |
-| 2 | Node A DROPs a table; B GETs it | B still reports it as present (cache hit) until the next poll | Accept — any write to it on B is re-validated against the DB and rejected as not-found, so no corruption |
-| 3 | RENAME (the old name behaves like a DROP); B GETs the old name | B keeps resolving the old name until the next poll; the new name misses → DB load | Same as DROP — bounded by the poll interval |
-| 4 | A property changes (e.g. Iceberg metadata-location); B GETs it | B returns the old location → a query on B may read an old snapshot/path | Highest-value case: offer a consistent (cache-bypass) read for location-sensitive callers, or use `redis` |
+The danger depends on where the real data comes from.
-**2. Read-your-writes across nodes.**
+**Group 1 — the data comes from the connector: table, view, topic, and schemas in external catalogs.** For these, Gravitino does not read the metadata from its own cache. On every load it asks the underlying system (Hive, Iceberg, JDBC, Kafka) for the current object, and uses the cached entity only for Gravitino's own id and audit fields. All nodes ask the same underlying system, so they all see the same thing. If the object was dropped or renamed, the connector call fails right away with a "not found" error. **This whole group is safe — nothing to do.**
-| # | Scenario | Effect | Possible mitigation |
-| - |---------------------------------------------------------------------|-------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
-| 5 | Through a load balancer, ALTER on A then an immediate read on B | Stale — violates session consistency; without sticky routing the change looks lost | Sticky sessions at the LB, or a client-supplied last-seen version that bypasses the cache when the copy is older; `redis` removes it entirely |
-| 6 | CREATE (rather than ALTER/DROP) | No problem — no negative caching and `list` skips the cache, so a new entity is visible at once | None needed |
+**Group 2 — the data comes from Gravitino's own store: metalake, catalog, managed schema, fileset, model, model version, function.** Here the cached entity *is* the answer, so a stale read really can return an old value. We looked at each alter in this group.
-**3. Cross-node read-modify-write.**
+(Views follow the same rule as tables: their definition is read through the connector on every load, so they sit in Group 1 and are safe.)
-| # | Scenario | Effect | Possible mitigation |
-| - | ------------------------------------------------------------------------------------- |-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------|
-| 7 | B reads stale value A and submits an update carrying A's version as the expected one | The optimistic lock rejects it on version mismatch — safe, but the user sees an unexpected conflict | Accept (correctness is preserved); reduce its frequency with the read-your-writes mitigations above |
+#### Walking through the alters in Group 2
-**4. Is the window actually bounded? — poller reliability (the real risk).** The "at most one poll interval" guarantee holds **only if the poller never drops a row**. If it does, the stale entry survives until the cache TTL, so this is the one place eventual consistency itself can break.
+Most alters are safe:
-| # | Scenario | Effect | Possible mitigation |
-| -- |-----------------------------------------------------------------------------------------------------------|-----------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------|
-| 8 | Commit-ordering gap / a skipped row | The key is never invalidated; stale until the TTL | Reuse the lag-safe, id-based polling already built for the change log (`#11736`); keep the cache TTL as a backstop |
-| 9 | Poller thread dies / DB briefly unreachable | That node serves stale data until the TTL | TTL backstop + monitor poller liveness/lag and alert |
-| 10 | Hierarchical DROP: only the container (schema) emits a row; children are cleared by a forward prefix scan | Correct as long as the prefix scan covers every child key | Cover with the hierarchical-drop test; confirm no child is written in a separate transaction that outlives the container row |
+| Change | What a stale read does | Safe? |
+| -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
+| rename (metalake, catalog, schema, fileset, model) | reading the old name returns a leftover copy, but any write to it goes to the DB and fails; the new name misses the cache and loads fresh from the DB | yes |
+| update comment | you see an old comment for a moment | yes |
+| set / remove property (metalake, model, fileset) | these properties do not change where the data lives | yes |
+| fileset storage location | **cannot be changed** — there is no alter for it, so it can never go stale | yes |
+| drop | for Group 1 the connector call fails; for a fileset the file path is gone and access fails | yes |
+| catalog changes | already handled today by a separate cross-node signal (`CatalogChangeLogListener`), not by this cache | yes |
-**5. Idempotency (no issue).** Replaying ALTER then DROP, in any order or duplicated, is safe: invalidation is idempotent, so out-of-order or repeated replay has no effect.
+Five cases are **not** safe — a stale read gives a wrong answer with no error. They are in the model area, functions, or the metalake on/off flag:
-#### Summary: main risks, resolutions, and the staleness SLA
+| Change | Why a stale read is wrong, with no error |
+| --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| model version — update / add / remove URI | the URI points to the model files. An old URI silently loads the **wrong model files**. |
+| model version — update aliases | an alias silently points to the **wrong version**. |
+| model — latest version (after a new version is added on another node) | "get the latest version" silently returns an **old version**. |
+| function — add / update / remove implementation or definition | the implementation is the code the function runs. An old copy silently runs the **wrong function code**. |
+| metalake — disable | a node with a stale copy still thinks the metalake is on and **lets operations run** on a metalake that was turned off. (Turning it back on is safe: a stale node only throws "in use" by mistake.) |
Review Comment:
Tags and policies are all self-managed and will also have consistency problems during the fresh window, so for the entity store cache, I plan to omit them temporarily.
I noticed that we are developing a feature: tag-based access control. I'm not sure whether the performance can be satisfied when we disable the cache for tags and policies.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3584964220
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -0,0 +1,412 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+---
+title: "Multi-Node Support for the Entity Store Cache"
+status: "Draft"
+date: "2026-07-07"
+---
+
+## Background
+
+Gravitino has two caches:
+
+- The **jcasbin authorization cache** already works with more than one node.
+- The **entity store cache** does not. When a change happens on node A, only node A clears its cache. Node B keeps serving the old data until its entry expires.
+
+Because of this, the only safe way to run more than one node today is to turn the entity store cache off (`gravitino.cache.enabled=false`). That is bad for read-heavy catalogs, especially Iceberg.
+
+This document proposes a design to make the entity store cache correct when running more than one node. It is a design proposal; no behavior has changed yet.
+
+## Goals and Non-Goals
+
+**Goals**
+
+- Make the entity store cache correct with more than one node, so `gravitino.cache.enabled=true` is safe.
+- Keep the cache **pluggable**: one SPI, chosen by `gravitino.cache.impl`. Ship `caffeine` as the default (no extra dependency) and `redis` as an option the user turns on by config. The current caffeine implementation is rather complex for any users to make any an new implementation, so we need to simplify it.
+- Keep single-node behavior and the write path (the optimistic version lock) unchanged.
+
+**Non-Goals**
+
+- Replace the entity store or its write path. The cache sits in front of the store and is never the source of truth.
+- Add a cluster membership / gossip layer or any other complex distributed system. We only use the DB Gravitino already needs, or the external cache the user turns on.
+
+---
+
+## Current Cache Implementation
+
+`EntityCache` is already an SPI, chosen by `gravitino.cache.impl` and created by `CacheFactory`. There is one implementation today, `CaffeineEntityCache` (`caffeine`): an in-memory cache, **one copy per node**, with two kinds of entries:
+
+- **entity keys** `(ident, type)` → the entity itself;
+- **relation keys** `(ident, type, relType)` → the list of related entities, stored **in both directions** and kept in step by an in-process **reverse index** (`ReverseIndexCache`).
+
+On a write, the node clears the changed key and then uses the reverse index to clear the related keys. On a single node this is correct. The problem is that this clearing happens **only on the node that made the change** (`RelationalEntityStore` calls `cache.invalidate(...)` locally). Nothing tells the other nodes, so they serve old data until their entries expire.
+
+Some behavior is already safe with more than one node and does not change:
+
+| Already correct | Why |
+| ------------------------- | ---------------------------------------------------------------------------- |
+| Writes never lose updates | The write path reads the DB (not the cache) with an optimistic version check |
+| `list(namespace)` | Skips the cache, so it is never stale |
+| CREATE | Needs nothing: no negative caching, and `list` skips the cache |
+
+The rest of the problem splits in two:
+
+- **entity keys** are one-to-one. "table T changed" names exactly the key to drop, and any node can drop it. This is easy.
+- **relation keys** have a reverse key. Dropping one side (say a role) also means dropping the other side's key (each user that had the role), but "the role changed" does not say *which* users those are. The writing node knows them from its local reverse index; a remote node may not.
+
+That reverse key is the hard part. So the first question is whether the cache needs relations at all.
+
+---
+
+## Do We Need to Cache Relations?
+
+All the cross-node difficulty comes from relation caching (the reverse key and the write fan-out). Before building around it, we checked whether it is actually important for performance. It is not.
+
+**Who reads the relation cache.** The cached relation path is `RelationalEntityStore.listEntitiesByRelation`, which runs **one indexed SQL join** per call (`JDBCBackend.listEntitiesByRelation`). Its callers are all metadata governance managers:
+
+| Caller | Relation | API that uses it |
+| -------------------- | ---------------------------- |-----------------------------------|
+| `OwnerManager` | `OWNER_REL` | `GET .../owner` |
+| `RoleManager` | role relations | role / authorization management |
+| `FutureGrantManager` | role/user/group relations | applying future grants (admin op) |
+| `TagManager` | `TAG_METADATA_OBJECT_REL` | tag endpoints |
+| `PolicyManager` | `POLICY_METADATA_OBJECT_REL` | policy endpoints |
+
+**Who does not.** The two paths that must be fast do **not** use it:
+
+- **Core metadata reads** (`get` / `list` of table, schema, catalog, …) never call `listEntitiesByRelation`. Removing the relation cache does not affect them at all.
+- **Authorization checks** (`JcasbinAuthorizer`) read roles straight from mappers (`RoleMetaMapper.listRolesByUserId` / `listRolesByGroupId`), owner from its own `ownerRelCache` (which polls `owner_meta`), and id from its own `metadataIdCache`. It does not use the entity store relation cache at all. Relation caching was first added with authorization in mind, but authorization no longer uses it.
+
+**Cost of removing it.** Each call becomes one indexed query — not an N+1 (one query per item). No list endpoint loads relations per item in a loop. The one place a single request makes several queries is **tag / policy inheritance**: listing an object's tags also reads its parents (the object plus up to ~3 ancestors), so a tag lookup is up to ~4 single-row queries; the cache mainly saves re-reading popular parents. This is the only workload where removing the cache adds real DB load, and it can be measured today — those calls are already `@Monitored` (`baseMetricName = "listTagsForMetadataObject"`, `"getOwner"`, `"listPoliciesForMetadataObject"`).
+
+**Decision.** Remove relation caching from the entity store cache. Relation reads go straight to the DB (one indexed query each), the same as authorization already does. This is safe for the core read path and for authorization; the only risk is workloads with heavy tag/policy inheritance reads, which we can watch with the existing metrics and, if ever needed, address by adding precise relation caching back later.
+
+The result: the cache holds only **entity keys**, so cross-node invalidation becomes the easy one-to-one case, and (as both implementations show) each design loses its hardest part. The `ReverseIndexCache` and the two-direction relation keys are removed with it.
+
+But "cache only entity keys" is not the end of it: some entities **copy fields from other entities**, which would bring the reverse-lookup problem back. The next section works out which entities are actually safe to cache.
+
+---
+
+## Which Entities to Cache
+
+Dropping relations leaves the entity keys. But not every entity key is truly one-to-one. Some entities store fields **copied from other entities**, and those copies go stale when the other entity changes — which brings back the same reverse lookup we just removed. So we look at what each cached entity actually holds.
+
+**Self-contained vs. derived.**
+
+| Entity | Copies a field from another entity? | Safe to cache on its own? |
+| ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
+| metalake, catalog, schema, table, topic, view, fileset | no — holds only its own data (columns, properties, comment…) | yes |
+| model, model version, function | no — but each holds a load-bearing pointer (the model version URI / latest version, or the function implementation) that goes stale on other nodes | no — left out for cross-node safety, see [Consistency](#consistency) |
+| tag, policy | no — associations are relations, not stored on the entity | yes |
+| user, group | yes — `roleNames` / `roleIds`, built from the user's roles | no |
+| role | yes — `securableObjects`, built from metadata objects | no |
+
+**Why user / group / role are a problem.**
+
+- `getUserByIdentifier` builds `roleNames` at read time by joining the user's roles (`UserMetaService` calls `RoleMetaService.listRolesByUserId`). If a role is dropped, it disappears from every user's list, but the user rows are not touched — so a cached user still lists the dropped role. Finding which users hold a role is a reverse lookup (role → users), exactly what dropping relations was meant to avoid.
+- `RoleEntity.securableObjects` has the same shape one level up: if a metadata object is renamed or dropped, a cached role that points at it is stale, and finding which roles point at an object is again a reverse lookup (object → roles).
+
+**Does authorization need these in the cache?** This is the key question, because authorization is the hot path. We checked `JcasbinAuthorizer`:
+
+- **user / group — no.** It reads user and group data through its own mappers (`UserMetaMapper`, `GroupMetaMapper`) into its own caches (`userRoleCache`, `groupRoleCache`), never through the entity store cache. So excluding user/group from the entity store cache does not affect authorization at all.
+- **role — only at cold start or after a change.** It does read role entities through the entity store (`entityStore.batchGet/get(ROLE)`), but only to (re)load a role's policies into the enforcer. Loaded roles are held in `loadedRoles`, a cache with `expireAfterAccess` (default 1 hour), so a role used at least once an hour never expires and the entity read is skipped. The entity read happens only on cold start, right after a role is edited, or after a role sits unused for over an hour — each a cheap one-time `batchGet`, not a per-request cost.
+
+So caching user, group, and role buys almost nothing (authorization does not depend on it) and costs a lot (the reverse-lookup problem comes back). tag and policy are safe to cache, but they are low-volume governance objects, not the read-heavy metadata the cache exists for.
+
+**Conclusion: cache only the basic metadata objects** — metalake, catalog, schema, table, topic, view, fileset. In code this is a small allowlist of entity types in the cache. Model, model version, and function are left out on purpose: they are read rarely, and each one holds a load-bearing pointer (the model version URI or latest version, or the function implementation) that would return a wrong answer on another node if it went stale — the per-alter check under [Consistency](#consistency) explains why. Every cached entity is then self-contained and one-to-one, so cross-node invalidation stays precise with no reverse lookups. As a bonus, these entities already write ALTER/DROP rows to `entity_change_log`, so the writer side needs no change at all.
+
+The cache now holds only self-contained metadata objects. The next question is how to tell the other nodes to drop a key when it changes.
+
+---
+
+## Approaches to Multi-Node Consistency
+
+Keeping a per-node cache fresh across a cluster is a common problem: after a write on one node, no other node may serve stale data. The standard techniques:
+
+| Approach | How it works | Trade-off |
+| -------------------------- | ------------------------------------------------------------------------------------------- |------------------------------------------------------------------------------------|
+| TTL only | each entry expires after a fixed time | no work, but every node serves old data until the TTL passes |
+| Pub/sub broadcast | the writer sends "invalidate X"; every node subscribes | low delay, but needs a message bus and must handle missed messages |
+| Change-log table + poller | the writer records the change in a DB table in the same transaction; each node polls it | no new infrastructure (reuses the DB), survives restarts; up to one poll of delay |
+| Shared (distributed) cache | one copy for the whole cluster, so there is nothing per-node to keep fresh | no propagation at all, but needs Redis/Memcached and a network round-trip per read |
+
+### How other metadata systems solve it
+
+We looked at how similar systems keep **their own per-node cache** coherent across a cluster (not how they notify downstream/derived systems — that is a different problem). **The most common answer is a per-node cache kept fresh by polling or by an invalidation/broadcast signal; no one relies on plain TTL.** Each row below has a source:
+
+| System | How it keeps its per-node cache fresh across nodes | Technique |
+| ---------------------------------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------|
+| **Hive Metastore** (`CachedStore`) | each node's in-memory cache is updated by a background thread that **polls the `NOTIFICATION_LOG` table** (written by `DbNotificationListener`); the log is in commit order and is the source of truth, and reads fall back to the DB until the thread catches up [1][2] | change-log + poll |
+| **Apache Ranger** (plugins) | each plugin keeps a **local policy cache** and **periodically polls Ranger Admin** for a newer version (default every 30s, `policy.pollIntervalMs`), downloading only the delta when the version changes [3] | periodic poll |
+| **Confluent Schema Registry** | one compacted Kafka topic **`_schemas`** is the commit log and the source of truth; every node reads it in a background thread to build its **local materialized view** [4] | shared log |
+| **Apache Impala** (`catalogd`) | metadata changes are **broadcast to all coordinators through `statestored`**; in local-catalog mode coordinators instead **fetch on demand and cache locally**, and invalidate that cache on `catalogd` failover [5] | broadcast / on-demand pull |
+| **Redis** (client-side caching) | with `CLIENT TRACKING` the server remembers which keys each client cached and **pushes an invalidation message** (RESP3 push) when a key changes, so the client flushes its local copy [6] | server-push invalidation |
+| **CockroachDB** | each node caches table/schema descriptors under a **versioned lease**; at most the **two latest versions** can be leased at once, and a schema change waits for old leases to be released or to expire (lease duration on the order of minutes) before advancing [7] | versioned lease |
+| **Trino** (Hive connector) | a coordinator-side metastore cache with a fixed **TTL plus background refresh** (`hive.metastore-cache-ttl`, `hive.metastore-refresh-interval`); its own docs note this can return stale data [8] | TTL + refresh |
+
+Two things stand out: **polling a change/version log (Hive, Ranger) is the most common, no-new-infrastructure answer**, and the one system that relies on **TTL alone (Trino) is documented to sometimes return stale data** — even CockroachDB, which looks TTL-like, actually uses bounded leases with active release, not plain expiry. That is exactly why TTL is not enough for us.
+
+### The two approaches we pick
+
+The closest match to what Gravitino needs is **Hive Metastore's `CachedStore`**: a per-node cache kept fresh by polling a change log in the same DB. Gravitino already has both pieces — the DB as the source of truth, and an `entity_change_log` table with a poller (built for the jcasbin cache). So this works with **no new infrastructure**. This is the default, and we call it `caffeine`.
+
+The broadcast / pub-sub-invalidation systems (Impala's `statestored`, Redis client-side caching, Schema Registry's shared log) work well, but they need a **message bus that Gravitino does not have**, so pub/sub is left for later (see the [roadmap](#roadmap)). **TTL alone** (Trino) is rejected for the stale-read reason its own docs give. That leaves two approaches that need no new component:
+
+- **reuse the DB** — a per-node cache kept fresh by the change log. → `caffeine`
+- **use a shared copy** — for teams already running Redis and wanting strong consistency, keep one copy in Redis. → `redis`
+
+**Sources**
+
+1. Hive — *Synchronized Metastore Cache*: <https://cwiki.apache.org/confluence/display/Hive/Synchronized+Metastore+Cache> (and HIVE-18661: <https://issues.apache.org/jira/browse/HIVE-18661>)
+2. Hive — `CachedStore.java` / `DbNotificationListener.java`: <https://github.com/apache/hive/blob/master/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/cache/CachedStore.java>
+3. Apache Ranger — *FAQ* (plugins cache policies locally and poll Ranger Admin at intervals): <https://ranger.apache.org/faq.html>; default `pollIntervalMs = 30000` in the plugin config: <https://github.com/apache/ranger/blob/master/hive-agent/conf/ranger-hive-security.xml>
+4. Confluent Schema Registry docs: <https://docs.confluent.io/platform/current/schema-registry/index.html>
+5. Apache Impala — *Metadata Management* (catalogd broadcasts via statestored; local-catalog mode fetches on demand and caches): <https://impala.apache.org/docs/build/html/topics/impala_metadata.html>
+6. Redis — *Client-side caching* / `CLIENT TRACKING` (RESP3 push invalidation): <https://redis.io/docs/latest/develop/reference/client-side-caching/>
+7. CockroachDB — *Table Descriptor Lease* RFC (at most two leased versions; ~5m lease): <https://github.com/cockroachdb/cockroach/blob/master/docs/RFCS/20151009_table_descriptor_lease.md> (and *Online Schema Changes*: <https://www.cockroachlabs.com/docs/stable/online-schema-changes>)
+8. Trino — *Metastores* docs: <https://trino.io/docs/current/object-storage/metastores.html> (stale-read note: <https://github.com/trinodb/trino/issues/10512>)
+
+---
+
+## The Pluggable Framework
+
+We now have two approaches that behave differently — one keeps a local copy per node, the other keeps one shared copy. To let a user pick either one by config, the cache stays **pluggable**, and each implementation says which kind it is. The `EntityCache` SPI adds one method:
+
+```
+EntityCache.coherence() → LOCAL_PER_NODE | SHARED
+```
+
+- `LOCAL_PER_NODE` — each node has its own copy, so a write must be **sent to the other nodes** to clear their copies. `caffeine` is this kind.
+- `SHARED` — one copy for the whole cluster, so a write clears it once and every node sees it. Nothing to send. `redis` is this kind.
+
+The write path is the same for both; only what happens after the local clear differs, and that is decided by `coherence()`:
+
+<!-- diagram source: diagrams/coherence-gate.mmd (regenerate with mermaid-cli) -->
+
+
+`CacheFactory.ENTITY_CACHES` is already a name → class table loaded by reflection, so adding `redis` next to `caffeine` is one new table entry with no change to the callers.
+
+The rest of this document describes each implementation — first the default local cache, then the shared cache.
+
+---
+
+# Implementation A — Caffeine (`caffeine`, `LOCAL_PER_NODE`, default)
+
+With only self-contained metadata objects cached, "entity X changed" names exactly the key to drop, and **any node can drop it** — no reverse key, no fan-out. The channel to carry "entity X changed" to the other nodes already exists and is already used by other caches.
+
+<!-- diagram source: diagrams/entity-key-invalidation.mmd (regenerate with mermaid-cli) -->
+
+
+### Reuse the existing transport
+
+`entity_change_log` and `EntityChangeLogPoller` already exist and are already used by two consumers:
+
+- `CatalogChangeLogListener` → clears `CatalogManager`'s catalog cache;
+- `JcasbinChangeListener` → clears jcasbin's **id-mapping cache** (`metadataIdCache`).
+
+Each row is `{metalake, entity_type, full_name, operate_type (ALTER | DROP), created_at}`. The structural MetaServices (metalake, catalog, schema, table, topic, view, fileset) already write a row on ALTER/DROP. We add the entity store cache as a **third consumer** of the same poller.
+
+### Writer side
+
+The cache now holds only metadata objects, and those **already write** an ALTER/DROP row to `entity_change_log` today. So the writer side needs **no change** — no new rows, no new columns, no new operate type:
+
+| Change | Cached? | Writes a change-log row |
+| ----------------------------------------------------- | ------- | ----------------------- |
+| structural ALTER/DROP (table, schema, catalog, …) | yes | yes — already emitted |
+| user / group / role / tag / policy ALTER/DROP | no | not needed (not cached) |
+| model / model version / function ALTER/DROP | no | not needed (not cached) |
+| relation change (grant, set owner, attach tag/policy) | no | not needed (not cached) |
+
+The existing structural rows are written in the same transaction as the entity write, so nothing new is added here.
+
+### Reader side
+
+A new `EntityChangeLogListener` for the entity store cache runs on the **same poller** and replays each row as a direct invalidation:
+
+```
+onEntityChange(rows):
+ for row in rows:
+ cache.invalidate(identOf(row), row.entity_type) # drop exactly this entity key
+```
+
+Dropping a container (for example a schema) must also drop its cached children. That uses the **forward** prefix scan the cache already has (`cacheIndex`), on the local node — the reverse index is not involved. This is the only remaining cascade.
+
+### A third consumer of the existing feed
+
+The entity store cache becomes a third consumer of the poller, next to the catalog cache and the jcasbin id-mapping cache. All three read the same structural ALTER/DROP rows that already exist — the entity store cache clears its entity key, the catalog cache clears its catalog, jcasbin clears its id mapping. There is no new row type, so the existing consumers do not change.
+
+### Consistency
+
+The cache never holds the truth. Every write goes to the DB first, under the version lock, so a stale cache can **never** cause a lost update or a bad write. The only thing that can go wrong is that a read on **another node** returns an old value for a short time — at most one poll interval, until that node drops the key.
+
+So the real question is simple: when another node reads an old value, does it matter? We went through every alter and every drop, for every cached entity, one at a time. A stale read falls into one of two buckets:
+
+- **The old value makes the next step fail with an error.** The user sees the error and tries again. This is safe.
+- **The old value is used silently and gives a wrong answer, with no error.** This is the dangerous kind.
+
+We only need to worry about the second bucket.
+
+#### Two groups of cached entities
+
+The danger depends on where the real data comes from.
+
+**Group 1 — the data comes from the connector: table, view, topic, and schemas in external catalogs.** For these, Gravitino does not read the metadata from its own cache. On every load it asks the underlying system (Hive, Iceberg, JDBC, Kafka) for the current object, and uses the cached entity only for Gravitino's own id and audit fields. All nodes ask the same underlying system, so they all see the same thing. If the object was dropped or renamed, the connector call fails right away with a "not found" error. **This whole group is safe — nothing to do.**
+
+**Group 2 — the data comes from Gravitino's own store: metalake, catalog, managed schema, fileset, model, model version, function.** Here the cached entity *is* the answer, so a stale read really can return an old value. We looked at each alter in this group.
+
+(Views follow the same rule as tables: their definition is read through the connector on every load, so they sit in Group 1 and are safe.)
+
+#### Walking through the alters in Group 2
+
+Most alters are safe:
+
+| Change | What a stale read does | Safe? |
+| -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
+| rename (metalake, catalog, schema, fileset, model) | reading the old name returns a leftover copy, but any write to it goes to the DB and fails; the new name misses the cache and loads fresh from the DB | yes |
+| update comment | you see an old comment for a moment | yes |
+| set / remove property (metalake, model, fileset) | these properties do not change where the data lives | yes |
+| fileset storage location | **cannot be changed** — there is no alter for it, so it can never go stale | yes |
+| drop | for Group 1 the connector call fails; for a fileset the file path is gone and access fails | yes |
+| catalog changes | already handled today by a separate cross-node signal (`CatalogChangeLogListener`), not by this cache | yes |
+
+Five cases are **not** safe — a stale read gives a wrong answer with no error. They are in the model area, functions, or the metalake on/off flag:
+
+| Change | Why a stale read is wrong, with no error |
+| --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| model version — update / add / remove URI | the URI points to the model files. An old URI silently loads the **wrong model files**. |
+| model version — update aliases | an alias silently points to the **wrong version**. |
+| model — latest version (after a new version is added on another node) | "get the latest version" silently returns an **old version**. |
+| function — add / update / remove implementation or definition | the implementation is the code the function runs. An old copy silently runs the **wrong function code**. |
+| metalake — disable | a node with a stale copy still thinks the metalake is on and **lets operations run** on a metalake that was turned off. (Turning it back on is safe: a stale node only throws "in use" by mistake.) |
+
+#### What we do about it
+
+We keep the simple design and remove the danger at the source:
+
+- **Do not cache the model area (model, model version) or functions.** The cache exists for the read-heavy path, which today is tables; model and function reads are a small share of traffic, so reading them from the DB every time costs almost nothing. Leaving these areas out removes four of the five dangerous cases outright and keeps the rule simple (an entity type is either in or out — no half-cached entity with a version-checked pointer). These reads are then always fresh, on every node. If model or function traffic grows later, we can add them back with a proper freshness check.
Review Comment:
@jerryshao
This is the final decision, and we will exclude entities of those types shortly.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#issuecomment-5021853752
> What is the status for now?
The design is stable, and I'm actively working on its subtasks.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3543992168
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -0,0 +1,350 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+---
+title: "Multi-Node Support for the Entity Store Cache"
+status: "Draft"
+date: "2026-07-07"
+---
+
+## Background
+
+Gravitino has two caches:
+
+- The **jcasbin authorization cache** already works with more than one node.
+- The **entity store cache** does not. When a change happens on node A, only node A clears its cache. Node B keeps serving the old data until its entry expires.
+
+Because of this, the only safe way to run more than one node today is to turn the entity store cache off (`gravitino.cache.enabled=false`). That is bad for read-heavy catalogs, especially Iceberg.
+
+This document proposes a design to make the entity store cache correct when running more than one node. It is a design proposal; no behavior has changed yet.
+
+## Goals and Non-Goals
+
+**Goals**
+
+- Make the entity store cache correct with more than one node, so `gravitino.cache.enabled=true` is safe.
+- Keep the cache **pluggable**: one SPI, chosen by `gravitino.cache.impl`. Ship `caffeine` as the default (no extra dependency) and `redis` as an option the user turns on by config.
+- Keep single-node behavior and the write path (the optimistic version lock) unchanged.
+
+**Non-Goals**
+
+- Replace the entity store or its write path. The cache sits in front of the store and is never the source of truth.
+- Add a cluster membership / gossip layer or any other complex distributed system. We only use the DB Gravitino already needs, or the external cache the user turns on.
+
+---
+
+## Current Cache Implementation
+
+`EntityCache` is already an SPI, chosen by `gravitino.cache.impl` and created by `CacheFactory`. There is one implementation today, `CaffeineEntityCache` (`caffeine`): an in-memory cache, **one copy per node**, with two kinds of entries:
+
+- **entity keys** `(ident, type)` → the entity itself;
+- **relation keys** `(ident, type, relType)` → the list of related entities, stored **in both directions** and kept in step by an in-process **reverse index** (`ReverseIndexCache`).
+
+On a write, the node clears the changed key and then uses the reverse index to clear the related keys. On a single node this is correct. The problem is that this clearing happens **only on the node that made the change** (`RelationalEntityStore` calls `cache.invalidate(...)` locally). Nothing tells the other nodes, so they serve old data until their entries expire.
+
+Some behavior is already safe with more than one node and does not change:
+
+| Already correct | Why |
+| ------------------------- | ---------------------------------------------------------------------------- |
+| Writes never lose updates | The write path reads the DB (not the cache) with an optimistic version check |
+| `list(namespace)` | Skips the cache, so it is never stale |
+| CREATE | Needs nothing: no negative caching, and `list` skips the cache |
+
+The rest of the problem splits in two:
+
+- **entity keys** are one-to-one. "table T changed" names exactly the key to drop, and any node can drop it. This is easy.
+- **relation keys** have a reverse key. Dropping one side (say a role) also means dropping the other side's key (each user that had the role), but "the role changed" does not say *which* users those are. The writing node knows them from its local reverse index; a remote node may not.
+
+That reverse key is the hard part. So the first question is whether the cache needs relations at all.
+
+---
+
+## Do We Need to Cache Relations?
+
+All the cross-node difficulty comes from relation caching (the reverse key and the write fan-out). Before building around it, we checked whether it is actually important for performance. It is not.
+
+**Who reads the relation cache.** The cached relation path is `RelationalEntityStore.listEntitiesByRelation`, which runs **one indexed SQL join** per call (`JDBCBackend.listEntitiesByRelation`). Its callers are all metadata governance managers:
+
+| Caller | Relation | API that uses it |
+| -------------------- | ---------------------------- |-----------------------------------|
+| `OwnerManager` | `OWNER_REL` | `GET .../owner` |
+| `RoleManager` | role relations | role / authorization management |
+| `FutureGrantManager` | role/user/group relations | applying future grants (admin op) |
+| `TagManager` | `TAG_METADATA_OBJECT_REL` | tag endpoints |
+| `PolicyManager` | `POLICY_METADATA_OBJECT_REL` | policy endpoints |
+
+**Who does not.** The two paths that must be fast do **not** use it:
+
+- **Core metadata reads** (`get` / `list` of table, schema, catalog, …) never call `listEntitiesByRelation`. Removing the relation cache does not affect them at all.
+- **Authorization checks** (`JcasbinAuthorizer`) read roles straight from mappers (`RoleMetaMapper.listRolesByUserId` / `listRolesByGroupId`), owner from its own `ownerRelCache` (which polls `owner_meta`), and id from its own `metadataIdCache`. It does not use the entity store relation cache at all. Relation caching was first added with authorization in mind, but authorization no longer uses it.
+
+**Cost of removing it.** Each call becomes one indexed query — not an N+1 (one query per item). No list endpoint loads relations per item in a loop. The one place a single request makes several queries is **tag / policy inheritance**: listing an object's tags also reads its parents (the object plus up to ~3 ancestors), so a tag lookup is up to ~4 single-row queries; the cache mainly saves re-reading popular parents. This is the only workload where removing the cache adds real DB load, and it can be measured today — those calls are already `@Monitored` (`baseMetricName = "listTagsForMetadataObject"`, `"getOwner"`, `"listPoliciesForMetadataObject"`).
+
+**Decision.** Remove relation caching from the entity store cache. Relation reads go straight to the DB (one indexed query each), the same as authorization already does. This is safe for the core read path and for authorization; the only risk is workloads with heavy tag/policy inheritance reads, which we can watch with the existing metrics and, if ever needed, address by adding precise relation caching back later.
+
+The result: the cache holds only **entity keys**, so cross-node invalidation becomes the easy one-to-one case, and (as both implementations show) each design loses its hardest part. The `ReverseIndexCache` and the two-direction relation keys are removed with it.
+
+But "cache only entity keys" is not the end of it: some entities **copy fields from other entities**, which would bring the reverse-lookup problem back. The next section works out which entities are actually safe to cache.
+
+---
+
+## Which Entities to Cache
+
+Dropping relations leaves the entity keys. But not every entity key is truly one-to-one. Some entities store fields **copied from other entities**, and those copies go stale when the other entity changes — which brings back the same reverse lookup we just removed. So we look at what each cached entity actually holds.
+
+**Self-contained vs. derived.**
+
+| Entity | Copies a field from another entity? | Safe to cache on its own? |
+| ------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------- |
+| metalake, catalog, schema, table, topic, model, view, fileset | no — holds only its own data (columns, properties, comment…) | yes |
+| tag, policy | no — associations are relations, not stored on the entity | yes |
+| user, group | yes — `roleNames` / `roleIds`, built from the user's roles | no |
+| role | yes — `securableObjects`, built from metadata objects | no |
+
+**Why user / group / role are a problem.**
+
+- `getUserByIdentifier` builds `roleNames` at read time by joining the user's roles (`UserMetaService` calls `RoleMetaService.listRolesByUserId`). If a role is dropped, it disappears from every user's list, but the user rows are not touched — so a cached user still lists the dropped role. Finding which users hold a role is a reverse lookup (role → users), exactly what dropping relations was meant to avoid.
+- `RoleEntity.securableObjects` has the same shape one level up: if a metadata object is renamed or dropped, a cached role that points at it is stale, and finding which roles point at an object is again a reverse lookup (object → roles).
+
+**Does authorization need these in the cache?** This is the key question, because authorization is the hot path. We checked `JcasbinAuthorizer`:
+
+- **user / group — no.** It reads user and group data through its own mappers (`UserMetaMapper`, `GroupMetaMapper`) into its own caches (`userRoleCache`, `groupRoleCache`), never through the entity store cache. So excluding user/group from the entity store cache does not affect authorization at all.
+- **role — only at cold start or after a change.** It does read role entities through the entity store (`entityStore.batchGet/get(ROLE)`), but only to (re)load a role's policies into the enforcer. Loaded roles are held in `loadedRoles`, a cache with `expireAfterAccess` (default 1 hour), so a role used at least once an hour never expires and the entity read is skipped. The entity read happens only on cold start, right after a role is edited, or after a role sits unused for over an hour — each a cheap one-time `batchGet`, not a per-request cost.
+
+So caching user, group, and role buys almost nothing (authorization does not depend on it) and costs a lot (the reverse-lookup problem comes back). tag and policy are safe to cache, but they are low-volume governance objects, not the read-heavy metadata the cache exists for.
+
+**Conclusion: cache only the basic metadata objects** — metalake, catalog, schema, table, topic, model, view, fileset. In code this is a small allowlist of entity types in the cache. Every cached entity is then self-contained and one-to-one, so cross-node invalidation stays precise with no reverse lookups. As a bonus, these entities already write ALTER/DROP rows to `entity_change_log`, so the writer side needs no change at all.
+
+The cache now holds only self-contained metadata objects. The next question is how to tell the other nodes to drop a key when it changes.
+
+---
+
+## Approaches to Multi-Node Consistency
+
+Keeping a per-node cache fresh across a cluster is a common problem: after a write on one node, no other node may serve stale data. The standard techniques:
+
+| Approach | How it works | Trade-off |
+| -------------------------- | ------------------------------------------------------------------------------------------- |------------------------------------------------------------------------------------|
+| TTL only | each entry expires after a fixed time | no work, but every node serves old data until the TTL passes |
+| Pub/sub broadcast | the writer sends "invalidate X"; every node subscribes | low delay, but needs a message bus and must handle missed messages |
+| Change-log table + poller | the writer records the change in a DB table in the same transaction; each node polls it | no new infrastructure (reuses the DB), survives restarts; up to one poll of delay |
+| Shared (distributed) cache | one copy for the whole cluster, so there is nothing per-node to keep fresh | no propagation at all, but needs Redis/Memcached and a network round-trip per read |
+
+### How other metadata systems solve it
+
+We looked at how similar systems keep **their own per-node cache** coherent across a cluster (not how they notify downstream/derived systems — that is a different problem). **The most common answer is a per-node cache kept fresh by polling or by an invalidation/broadcast signal; no one relies on plain TTL.** Each row below has a source:
+
+| System | How it keeps its per-node cache fresh across nodes | Technique |
+| ---------------------------------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------|
+| **Hive Metastore** (`CachedStore`) | each node's in-memory cache is updated by a background thread that **polls the `NOTIFICATION_LOG` table** (written by `DbNotificationListener`); the log is in commit order and is the source of truth, and reads fall back to the DB until the thread catches up [1][2] | change-log + poll |
+| **Apache Ranger** (plugins) | each plugin keeps a **local policy cache** and **periodically polls Ranger Admin** for a newer version (default every 30s, `policy.pollIntervalMs`), downloading only the delta when the version changes [3] | periodic poll |
+| **Confluent Schema Registry** | one compacted Kafka topic **`_schemas`** is the commit log and the source of truth; every node reads it in a background thread to build its **local materialized view** [4] | shared log |
+| **Apache Impala** (`catalogd`) | metadata changes are **broadcast to all coordinators through `statestored`**; in local-catalog mode coordinators instead **fetch on demand and cache locally**, and invalidate that cache on `catalogd` failover [5] | broadcast / on-demand pull |
+| **Redis** (client-side caching) | with `CLIENT TRACKING` the server remembers which keys each client cached and **pushes an invalidation message** (RESP3 push) when a key changes, so the client flushes its local copy [6] | server-push invalidation |
+| **CockroachDB** | each node caches table/schema descriptors under a **versioned lease**; at most the **two latest versions** can be leased at once, and a schema change waits for old leases to be released or to expire (lease duration on the order of minutes) before advancing [7] | versioned lease |
+| **Trino** (Hive connector) | a coordinator-side metastore cache with a fixed **TTL plus background refresh** (`hive.metastore-cache-ttl`, `hive.metastore-refresh-interval`); its own docs note this can return stale data [8] | TTL + refresh |
+
+Two things stand out: **polling a change/version log (Hive, Ranger) is the most common, no-new-infrastructure answer**, and the one system that relies on **TTL alone (Trino) is documented to sometimes return stale data** — even CockroachDB, which looks TTL-like, actually uses bounded leases with active release, not plain expiry. That is exactly why TTL is not enough for us.
+
+### The two approaches we pick
+
+The closest match to what Gravitino needs is **Hive Metastore's `CachedStore`**: a per-node cache kept fresh by polling a change log in the same DB. Gravitino already has both pieces — the DB as the source of truth, and an `entity_change_log` table with a poller (built for the jcasbin cache). So this works with **no new infrastructure**. This is the default, and we call it `caffeine`.
+
+The broadcast / pub-sub-invalidation systems (Impala's `statestored`, Redis client-side caching, Schema Registry's shared log) work well, but they need a **message bus that Gravitino does not have**, so pub/sub is left for later (see the [roadmap](#roadmap)). **TTL alone** (Trino) is rejected for the stale-read reason its own docs give. That leaves two approaches that need no new component:
+
+- **reuse the DB** — a per-node cache kept fresh by the change log. → `caffeine`
+- **use a shared copy** — for teams already running Redis and wanting strong consistency, keep one copy in Redis. → `redis`
+
+**Sources**
+
+1. Hive — *Synchronized Metastore Cache*: <https://cwiki.apache.org/confluence/display/Hive/Synchronized+Metastore+Cache> (and HIVE-18661: <https://issues.apache.org/jira/browse/HIVE-18661>)
+2. Hive — `CachedStore.java` / `DbNotificationListener.java`: <https://github.com/apache/hive/blob/master/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/cache/CachedStore.java>
+3. Apache Ranger — *FAQ* (plugins cache policies locally and poll Ranger Admin at intervals): <https://ranger.apache.org/faq.html>; default `pollIntervalMs = 30000` in the plugin config: <https://github.com/apache/ranger/blob/master/hive-agent/conf/ranger-hive-security.xml>
+4. Confluent Schema Registry docs: <https://docs.confluent.io/platform/current/schema-registry/index.html>
+5. Apache Impala — *Metadata Management* (catalogd broadcasts via statestored; local-catalog mode fetches on demand and caches): <https://impala.apache.org/docs/build/html/topics/impala_metadata.html>
+6. Redis — *Client-side caching* / `CLIENT TRACKING` (RESP3 push invalidation): <https://redis.io/docs/latest/develop/reference/client-side-caching/>
+7. CockroachDB — *Table Descriptor Lease* RFC (at most two leased versions; ~5m lease): <https://github.com/cockroachdb/cockroach/blob/master/docs/RFCS/20151009_table_descriptor_lease.md> (and *Online Schema Changes*: <https://www.cockroachlabs.com/docs/stable/online-schema-changes>)
+8. Trino — *Metastores* docs: <https://trino.io/docs/current/object-storage/metastores.html> (stale-read note: <https://github.com/trinodb/trino/issues/10512>)
+
+---
+
+## The Pluggable Framework
+
+We now have two approaches that behave differently — one keeps a local copy per node, the other keeps one shared copy. To let a user pick either one by config, the cache stays **pluggable**, and each implementation says which kind it is. The `EntityCache` SPI adds one method:
+
+```
+EntityCache.coherence() → LOCAL_PER_NODE | SHARED
+```
+
+- `LOCAL_PER_NODE` — each node has its own copy, so a write must be **sent to the other nodes** to clear their copies. `caffeine` is this kind.
+- `SHARED` — one copy for the whole cluster, so a write clears it once and every node sees it. Nothing to send. `redis` is this kind.
+
+The write path is the same for both; only what happens after the local clear differs, and that is decided by `coherence()`:
+
+<!-- diagram source: diagrams/coherence-gate.mmd (regenerate with mermaid-cli) -->
+
+
+`CacheFactory.ENTITY_CACHES` is already a name → class table loaded by reflection, so adding `redis` next to `caffeine` is one new table entry with no change to the callers.
+
+The rest of this document describes each implementation — first the default local cache, then the shared cache.
+
+---
+
+# Implementation A — Caffeine (`caffeine`, `LOCAL_PER_NODE`, default)
+
+With only self-contained metadata objects cached, "entity X changed" names exactly the key to drop, and **any node can drop it** — no reverse key, no fan-out. The channel to carry "entity X changed" to the other nodes already exists and is already used by other caches.
+
+<!-- diagram source: diagrams/entity-key-invalidation.mmd (regenerate with mermaid-cli) -->
+
+
+### Reuse the existing transport
+
+`entity_change_log` and `EntityChangeLogPoller` already exist and are already used by two consumers:
+
+- `CatalogChangeLogListener` → clears `CatalogManager`'s catalog cache;
+- `JcasbinChangeListener` → clears jcasbin's **id-mapping cache** (`metadataIdCache`).
+
+Each row is `{metalake, entity_type, full_name, operate_type (ALTER | DROP), created_at}`. The structural MetaServices (metalake, catalog, schema, table, topic, model, view, fileset) already write a row on ALTER/DROP. We add the entity store cache as a **third consumer** of the same poller.
+
+### Writer side
+
+The cache now holds only metadata objects, and those **already write** an ALTER/DROP row to `entity_change_log` today. So the writer side needs **no change** — no new rows, no new columns, no new operate type:
+
+| Change | Cached? | Writes a change-log row |
+| ----------------------------------------------------- | ------- | ----------------------- |
+| structural ALTER/DROP (table, schema, catalog, …) | yes | yes — already emitted |
+| user / group / role / tag / policy ALTER/DROP | no | not needed (not cached) |
+| relation change (grant, set owner, attach tag/policy) | no | not needed (not cached) |
+
+The existing structural rows are written in the same transaction as the entity write, so nothing new is added here.
+
+### Reader side
+
+A new `EntityChangeLogListener` for the entity store cache runs on the **same poller** and replays each row as a direct invalidation:
+
+```
+onEntityChange(rows):
+ for row in rows:
+ cache.invalidate(identOf(row), row.entity_type) # drop exactly this entity key
+```
+
+Dropping a container (for example a schema) must also drop its cached children. That uses the **forward** prefix scan the cache already has (`cacheIndex`), on the local node — the reverse index is not involved. This is the only remaining cascade.
Review Comment:
How do you guarantee the strong consistency by using polling mechanism? My feeling is that you can only achieve the final consistency with this change log solution, right?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3543971648
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -0,0 +1,350 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+---
+title: "Multi-Node Support for the Entity Store Cache"
+status: "Draft"
+date: "2026-07-07"
+---
+
+## Background
+
+Gravitino has two caches:
+
+- The **jcasbin authorization cache** already works with more than one node.
+- The **entity store cache** does not. When a change happens on node A, only node A clears its cache. Node B keeps serving the old data until its entry expires.
+
+Because of this, the only safe way to run more than one node today is to turn the entity store cache off (`gravitino.cache.enabled=false`). That is bad for read-heavy catalogs, especially Iceberg.
+
+This document proposes a design to make the entity store cache correct when running more than one node. It is a design proposal; no behavior has changed yet.
+
+## Goals and Non-Goals
+
+**Goals**
+
+- Make the entity store cache correct with more than one node, so `gravitino.cache.enabled=true` is safe.
+- Keep the cache **pluggable**: one SPI, chosen by `gravitino.cache.impl`. Ship `caffeine` as the default (no extra dependency) and `redis` as an option the user turns on by config.
+- Keep single-node behavior and the write path (the optimistic version lock) unchanged.
+
+**Non-Goals**
+
+- Replace the entity store or its write path. The cache sits in front of the store and is never the source of truth.
+- Add a cluster membership / gossip layer or any other complex distributed system. We only use the DB Gravitino already needs, or the external cache the user turns on.
+
+---
+
+## Current Cache Implementation
+
+`EntityCache` is already an SPI, chosen by `gravitino.cache.impl` and created by `CacheFactory`. There is one implementation today, `CaffeineEntityCache` (`caffeine`): an in-memory cache, **one copy per node**, with two kinds of entries:
+
+- **entity keys** `(ident, type)` → the entity itself;
+- **relation keys** `(ident, type, relType)` → the list of related entities, stored **in both directions** and kept in step by an in-process **reverse index** (`ReverseIndexCache`).
+
+On a write, the node clears the changed key and then uses the reverse index to clear the related keys. On a single node this is correct. The problem is that this clearing happens **only on the node that made the change** (`RelationalEntityStore` calls `cache.invalidate(...)` locally). Nothing tells the other nodes, so they serve old data until their entries expire.
+
+Some behavior is already safe with more than one node and does not change:
+
+| Already correct | Why |
+| ------------------------- | ---------------------------------------------------------------------------- |
+| Writes never lose updates | The write path reads the DB (not the cache) with an optimistic version check |
+| `list(namespace)` | Skips the cache, so it is never stale |
+| CREATE | Needs nothing: no negative caching, and `list` skips the cache |
+
+The rest of the problem splits in two:
+
+- **entity keys** are one-to-one. "table T changed" names exactly the key to drop, and any node can drop it. This is easy.
+- **relation keys** have a reverse key. Dropping one side (say a role) also means dropping the other side's key (each user that had the role), but "the role changed" does not say *which* users those are. The writing node knows them from its local reverse index; a remote node may not.
+
+That reverse key is the hard part. So the first question is whether the cache needs relations at all.
+
+---
+
+## Do We Need to Cache Relations?
+
+All the cross-node difficulty comes from relation caching (the reverse key and the write fan-out). Before building around it, we checked whether it is actually important for performance. It is not.
+
+**Who reads the relation cache.** The cached relation path is `RelationalEntityStore.listEntitiesByRelation`, which runs **one indexed SQL join** per call (`JDBCBackend.listEntitiesByRelation`). Its callers are all metadata governance managers:
+
+| Caller | Relation | API that uses it |
+| -------------------- | ---------------------------- |-----------------------------------|
+| `OwnerManager` | `OWNER_REL` | `GET .../owner` |
+| `RoleManager` | role relations | role / authorization management |
+| `FutureGrantManager` | role/user/group relations | applying future grants (admin op) |
+| `TagManager` | `TAG_METADATA_OBJECT_REL` | tag endpoints |
+| `PolicyManager` | `POLICY_METADATA_OBJECT_REL` | policy endpoints |
+
+**Who does not.** The two paths that must be fast do **not** use it:
+
+- **Core metadata reads** (`get` / `list` of table, schema, catalog, …) never call `listEntitiesByRelation`. Removing the relation cache does not affect them at all.
+- **Authorization checks** (`JcasbinAuthorizer`) read roles straight from mappers (`RoleMetaMapper.listRolesByUserId` / `listRolesByGroupId`), owner from its own `ownerRelCache` (which polls `owner_meta`), and id from its own `metadataIdCache`. It does not use the entity store relation cache at all. Relation caching was first added with authorization in mind, but authorization no longer uses it.
+
+**Cost of removing it.** Each call becomes one indexed query — not an N+1 (one query per item). No list endpoint loads relations per item in a loop. The one place a single request makes several queries is **tag / policy inheritance**: listing an object's tags also reads its parents (the object plus up to ~3 ancestors), so a tag lookup is up to ~4 single-row queries; the cache mainly saves re-reading popular parents. This is the only workload where removing the cache adds real DB load, and it can be measured today — those calls are already `@Monitored` (`baseMetricName = "listTagsForMetadataObject"`, `"getOwner"`, `"listPoliciesForMetadataObject"`).
+
+**Decision.** Remove relation caching from the entity store cache. Relation reads go straight to the DB (one indexed query each), the same as authorization already does. This is safe for the core read path and for authorization; the only risk is workloads with heavy tag/policy inheritance reads, which we can watch with the existing metrics and, if ever needed, address by adding precise relation caching back later.
+
+The result: the cache holds only **entity keys**, so cross-node invalidation becomes the easy one-to-one case, and (as both implementations show) each design loses its hardest part. The `ReverseIndexCache` and the two-direction relation keys are removed with it.
+
+But "cache only entity keys" is not the end of it: some entities **copy fields from other entities**, which would bring the reverse-lookup problem back. The next section works out which entities are actually safe to cache.
+
+---
+
+## Which Entities to Cache
+
+Dropping relations leaves the entity keys. But not every entity key is truly one-to-one. Some entities store fields **copied from other entities**, and those copies go stale when the other entity changes — which brings back the same reverse lookup we just removed. So we look at what each cached entity actually holds.
+
+**Self-contained vs. derived.**
+
+| Entity | Copies a field from another entity? | Safe to cache on its own? |
+| ------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------- |
+| metalake, catalog, schema, table, topic, model, view, fileset | no — holds only its own data (columns, properties, comment…) | yes |
+| tag, policy | no — associations are relations, not stored on the entity | yes |
+| user, group | yes — `roleNames` / `roleIds`, built from the user's roles | no |
+| role | yes — `securableObjects`, built from metadata objects | no |
+
+**Why user / group / role are a problem.**
+
+- `getUserByIdentifier` builds `roleNames` at read time by joining the user's roles (`UserMetaService` calls `RoleMetaService.listRolesByUserId`). If a role is dropped, it disappears from every user's list, but the user rows are not touched — so a cached user still lists the dropped role. Finding which users hold a role is a reverse lookup (role → users), exactly what dropping relations was meant to avoid.
+- `RoleEntity.securableObjects` has the same shape one level up: if a metadata object is renamed or dropped, a cached role that points at it is stale, and finding which roles point at an object is again a reverse lookup (object → roles).
+
+**Does authorization need these in the cache?** This is the key question, because authorization is the hot path. We checked `JcasbinAuthorizer`:
+
+- **user / group — no.** It reads user and group data through its own mappers (`UserMetaMapper`, `GroupMetaMapper`) into its own caches (`userRoleCache`, `groupRoleCache`), never through the entity store cache. So excluding user/group from the entity store cache does not affect authorization at all.
+- **role — only at cold start or after a change.** It does read role entities through the entity store (`entityStore.batchGet/get(ROLE)`), but only to (re)load a role's policies into the enforcer. Loaded roles are held in `loadedRoles`, a cache with `expireAfterAccess` (default 1 hour), so a role used at least once an hour never expires and the entity read is skipped. The entity read happens only on cold start, right after a role is edited, or after a role sits unused for over an hour — each a cheap one-time `batchGet`, not a per-request cost.
+
+So caching user, group, and role buys almost nothing (authorization does not depend on it) and costs a lot (the reverse-lookup problem comes back). tag and policy are safe to cache, but they are low-volume governance objects, not the read-heavy metadata the cache exists for.
+
+**Conclusion: cache only the basic metadata objects** — metalake, catalog, schema, table, topic, model, view, fileset. In code this is a small allowlist of entity types in the cache. Every cached entity is then self-contained and one-to-one, so cross-node invalidation stays precise with no reverse lookups. As a bonus, these entities already write ALTER/DROP rows to `entity_change_log`, so the writer side needs no change at all.
+
+The cache now holds only self-contained metadata objects. The next question is how to tell the other nodes to drop a key when it changes.
+
+---
+
+## Approaches to Multi-Node Consistency
+
+Keeping a per-node cache fresh across a cluster is a common problem: after a write on one node, no other node may serve stale data. The standard techniques:
+
+| Approach | How it works | Trade-off |
+| -------------------------- | ------------------------------------------------------------------------------------------- |------------------------------------------------------------------------------------|
+| TTL only | each entry expires after a fixed time | no work, but every node serves old data until the TTL passes |
+| Pub/sub broadcast | the writer sends "invalidate X"; every node subscribes | low delay, but needs a message bus and must handle missed messages |
+| Change-log table + poller | the writer records the change in a DB table in the same transaction; each node polls it | no new infrastructure (reuses the DB), survives restarts; up to one poll of delay |
+| Shared (distributed) cache | one copy for the whole cluster, so there is nothing per-node to keep fresh | no propagation at all, but needs Redis/Memcached and a network round-trip per read |
+
+### How other metadata systems solve it
+
+We looked at how similar systems keep **their own per-node cache** coherent across a cluster (not how they notify downstream/derived systems — that is a different problem). **The most common answer is a per-node cache kept fresh by polling or by an invalidation/broadcast signal; no one relies on plain TTL.** Each row below has a source:
+
+| System | How it keeps its per-node cache fresh across nodes | Technique |
+| ---------------------------------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------|
+| **Hive Metastore** (`CachedStore`) | each node's in-memory cache is updated by a background thread that **polls the `NOTIFICATION_LOG` table** (written by `DbNotificationListener`); the log is in commit order and is the source of truth, and reads fall back to the DB until the thread catches up [1][2] | change-log + poll |
+| **Apache Ranger** (plugins) | each plugin keeps a **local policy cache** and **periodically polls Ranger Admin** for a newer version (default every 30s, `policy.pollIntervalMs`), downloading only the delta when the version changes [3] | periodic poll |
+| **Confluent Schema Registry** | one compacted Kafka topic **`_schemas`** is the commit log and the source of truth; every node reads it in a background thread to build its **local materialized view** [4] | shared log |
+| **Apache Impala** (`catalogd`) | metadata changes are **broadcast to all coordinators through `statestored`**; in local-catalog mode coordinators instead **fetch on demand and cache locally**, and invalidate that cache on `catalogd` failover [5] | broadcast / on-demand pull |
+| **Redis** (client-side caching) | with `CLIENT TRACKING` the server remembers which keys each client cached and **pushes an invalidation message** (RESP3 push) when a key changes, so the client flushes its local copy [6] | server-push invalidation |
+| **CockroachDB** | each node caches table/schema descriptors under a **versioned lease**; at most the **two latest versions** can be leased at once, and a schema change waits for old leases to be released or to expire (lease duration on the order of minutes) before advancing [7] | versioned lease |
+| **Trino** (Hive connector) | a coordinator-side metastore cache with a fixed **TTL plus background refresh** (`hive.metastore-cache-ttl`, `hive.metastore-refresh-interval`); its own docs note this can return stale data [8] | TTL + refresh |
+
+Two things stand out: **polling a change/version log (Hive, Ranger) is the most common, no-new-infrastructure answer**, and the one system that relies on **TTL alone (Trino) is documented to sometimes return stale data** — even CockroachDB, which looks TTL-like, actually uses bounded leases with active release, not plain expiry. That is exactly why TTL is not enough for us.
+
+### The two approaches we pick
+
+The closest match to what Gravitino needs is **Hive Metastore's `CachedStore`**: a per-node cache kept fresh by polling a change log in the same DB. Gravitino already has both pieces — the DB as the source of truth, and an `entity_change_log` table with a poller (built for the jcasbin cache). So this works with **no new infrastructure**. This is the default, and we call it `caffeine`.
+
+The broadcast / pub-sub-invalidation systems (Impala's `statestored`, Redis client-side caching, Schema Registry's shared log) work well, but they need a **message bus that Gravitino does not have**, so pub/sub is left for later (see the [roadmap](#roadmap)). **TTL alone** (Trino) is rejected for the stale-read reason its own docs give. That leaves two approaches that need no new component:
+
+- **reuse the DB** — a per-node cache kept fresh by the change log. → `caffeine`
+- **use a shared copy** — for teams already running Redis and wanting strong consistency, keep one copy in Redis. → `redis`
+
+**Sources**
+
+1. Hive — *Synchronized Metastore Cache*: <https://cwiki.apache.org/confluence/display/Hive/Synchronized+Metastore+Cache> (and HIVE-18661: <https://issues.apache.org/jira/browse/HIVE-18661>)
+2. Hive — `CachedStore.java` / `DbNotificationListener.java`: <https://github.com/apache/hive/blob/master/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/cache/CachedStore.java>
+3. Apache Ranger — *FAQ* (plugins cache policies locally and poll Ranger Admin at intervals): <https://ranger.apache.org/faq.html>; default `pollIntervalMs = 30000` in the plugin config: <https://github.com/apache/ranger/blob/master/hive-agent/conf/ranger-hive-security.xml>
+4. Confluent Schema Registry docs: <https://docs.confluent.io/platform/current/schema-registry/index.html>
+5. Apache Impala — *Metadata Management* (catalogd broadcasts via statestored; local-catalog mode fetches on demand and caches): <https://impala.apache.org/docs/build/html/topics/impala_metadata.html>
+6. Redis — *Client-side caching* / `CLIENT TRACKING` (RESP3 push invalidation): <https://redis.io/docs/latest/develop/reference/client-side-caching/>
+7. CockroachDB — *Table Descriptor Lease* RFC (at most two leased versions; ~5m lease): <https://github.com/cockroachdb/cockroach/blob/master/docs/RFCS/20151009_table_descriptor_lease.md> (and *Online Schema Changes*: <https://www.cockroachlabs.com/docs/stable/online-schema-changes>)
+8. Trino — *Metastores* docs: <https://trino.io/docs/current/object-storage/metastores.html> (stale-read note: <https://github.com/trinodb/trino/issues/10512>)
+
+---
+
+## The Pluggable Framework
+
+We now have two approaches that behave differently — one keeps a local copy per node, the other keeps one shared copy. To let a user pick either one by config, the cache stays **pluggable**, and each implementation says which kind it is. The `EntityCache` SPI adds one method:
+
+```
+EntityCache.coherence() → LOCAL_PER_NODE | SHARED
+```
+
+- `LOCAL_PER_NODE` — each node has its own copy, so a write must be **sent to the other nodes** to clear their copies. `caffeine` is this kind.
+- `SHARED` — one copy for the whole cluster, so a write clears it once and every node sees it. Nothing to send. `redis` is this kind.
+
+The write path is the same for both; only what happens after the local clear differs, and that is decided by `coherence()`:
+
+<!-- diagram source: diagrams/coherence-gate.mmd (regenerate with mermaid-cli) -->
+
+
+`CacheFactory.ENTITY_CACHES` is already a name → class table loaded by reflection, so adding `redis` next to `caffeine` is one new table entry with no change to the callers.
+
+The rest of this document describes each implementation — first the default local cache, then the shared cache.
+
+---
+
+# Implementation A — Caffeine (`caffeine`, `LOCAL_PER_NODE`, default)
+
+With only self-contained metadata objects cached, "entity X changed" names exactly the key to drop, and **any node can drop it** — no reverse key, no fan-out. The channel to carry "entity X changed" to the other nodes already exists and is already used by other caches.
+
+<!-- diagram source: diagrams/entity-key-invalidation.mmd (regenerate with mermaid-cli) -->
+
+
+### Reuse the existing transport
+
+`entity_change_log` and `EntityChangeLogPoller` already exist and are already used by two consumers:
Review Comment:
Do you still need a db version checkpoint mechanism to keep the consistency for this change log poll solution?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11737] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#issuecomment-4781198088
<!-- coverage-report -->
### Code Coverage Report
|Overall Project|67.16%|:green_circle:|
|:-|:-|:-:|
|Files changed|No Java source files changed|-|
<br>
|Module|Coverage||
|:-|:-|:-:|
|aliyun|1.72%|:red_circle:|
|api|46.82%|:green_circle:|
|authorization-common|85.96%|:green_circle:|
|aws|3.66%|:red_circle:|
|azure|2.47%|:red_circle:|
|catalog-common|10.4%|:red_circle:|
|catalog-fileset|80.23%|:green_circle:|
|catalog-glue|66.91%|:green_circle:|
|catalog-hive|79.42%|:green_circle:|
|catalog-jdbc-clickhouse|80.02%|:green_circle:|
|catalog-jdbc-common|44.22%|:green_circle:|
|catalog-jdbc-doris|80.28%|:green_circle:|
|catalog-jdbc-hologres|54.03%|:green_circle:|
|catalog-jdbc-mysql|79.23%|:green_circle:|
|catalog-jdbc-oceanbase|80.91%|:green_circle:|
|catalog-jdbc-postgresql|82.29%|:green_circle:|
|catalog-jdbc-starrocks|78.51%|:green_circle:|
|catalog-kafka|77.01%|:green_circle:|
|catalog-lakehouse-generic|58.53%|:green_circle:|
|catalog-lakehouse-hudi|79.1%|:green_circle:|
|catalog-lakehouse-iceberg|85.86%|:green_circle:|
|catalog-lakehouse-paimon|82.14%|:green_circle:|
|catalog-model|77.72%|:green_circle:|
|cli|44.51%|:green_circle:|
|client-java|78.01%|:green_circle:|
|common|50.17%|:green_circle:|
|core|82.59%|:green_circle:|
|filesystem-hadoop3|77.27%|:green_circle:|
|flink|0.0%|:red_circle:|
|flink-common|47.12%|:green_circle:|
|flink-runtime|0.0%|:red_circle:|
|gcp|14.12%|:red_circle:|
|hadoop-common|10.88%|:red_circle:|
|hive-metastore-common|53.77%|:green_circle:|
|iceberg-common|58.15%|:green_circle:|
|iceberg-rest-server|73.9%|:green_circle:|
|idp-basic|85.71%|:green_circle:|
|integration-test-common|0.0%|:red_circle:|
|jobs|66.17%|:green_circle:|
|lance-common|20.83%|:red_circle:|
|lance-rest-server|60.13%|:green_circle:|
|lineage|53.02%|:green_circle:|
|optimizer|82.95%|:green_circle:|
|optimizer-api|21.95%|:red_circle:|
|server|85.96%|:green_circle:|
|server-common|74.18%|:green_circle:|
|spark|28.57%|:red_circle:|
|spark-common|41.66%|:green_circle:|
|trino-connector|40.25%|:green_circle:|
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3556053024
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -0,0 +1,395 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+---
+title: "Multi-Node Support for the Entity Store Cache"
+status: "Draft"
+date: "2026-07-07"
+---
+
+## Background
+
+Gravitino has two caches:
+
+- The **jcasbin authorization cache** already works with more than one node.
+- The **entity store cache** does not. When a change happens on node A, only node A clears its cache. Node B keeps serving the old data until its entry expires.
+
+Because of this, the only safe way to run more than one node today is to turn the entity store cache off (`gravitino.cache.enabled=false`). That is bad for read-heavy catalogs, especially Iceberg.
+
+This document proposes a design to make the entity store cache correct when running more than one node. It is a design proposal; no behavior has changed yet.
+
+## Goals and Non-Goals
+
+**Goals**
+
+- Make the entity store cache correct with more than one node, so `gravitino.cache.enabled=true` is safe.
+- Keep the cache **pluggable**: one SPI, chosen by `gravitino.cache.impl`. Ship `caffeine` as the default (no extra dependency) and `redis` as an option the user turns on by config. The current caffeine implementation is rather complex for any users to make any an new implementation, so we need to simplify it.
+- Keep single-node behavior and the write path (the optimistic version lock) unchanged.
+
+**Non-Goals**
+
+- Replace the entity store or its write path. The cache sits in front of the store and is never the source of truth.
+- Add a cluster membership / gossip layer or any other complex distributed system. We only use the DB Gravitino already needs, or the external cache the user turns on.
+
+---
+
+## Current Cache Implementation
+
+`EntityCache` is already an SPI, chosen by `gravitino.cache.impl` and created by `CacheFactory`. There is one implementation today, `CaffeineEntityCache` (`caffeine`): an in-memory cache, **one copy per node**, with two kinds of entries:
+
+- **entity keys** `(ident, type)` → the entity itself;
+- **relation keys** `(ident, type, relType)` → the list of related entities, stored **in both directions** and kept in step by an in-process **reverse index** (`ReverseIndexCache`).
+
+On a write, the node clears the changed key and then uses the reverse index to clear the related keys. On a single node this is correct. The problem is that this clearing happens **only on the node that made the change** (`RelationalEntityStore` calls `cache.invalidate(...)` locally). Nothing tells the other nodes, so they serve old data until their entries expire.
+
+Some behavior is already safe with more than one node and does not change:
+
+| Already correct | Why |
+| ------------------------- | ---------------------------------------------------------------------------- |
+| Writes never lose updates | The write path reads the DB (not the cache) with an optimistic version check |
+| `list(namespace)` | Skips the cache, so it is never stale |
+| CREATE | Needs nothing: no negative caching, and `list` skips the cache |
+
+The rest of the problem splits in two:
+
+- **entity keys** are one-to-one. "table T changed" names exactly the key to drop, and any node can drop it. This is easy.
+- **relation keys** have a reverse key. Dropping one side (say a role) also means dropping the other side's key (each user that had the role), but "the role changed" does not say *which* users those are. The writing node knows them from its local reverse index; a remote node may not.
+
+That reverse key is the hard part. So the first question is whether the cache needs relations at all.
+
+---
+
+## Do We Need to Cache Relations?
+
+All the cross-node difficulty comes from relation caching (the reverse key and the write fan-out). Before building around it, we checked whether it is actually important for performance. It is not.
+
+**Who reads the relation cache.** The cached relation path is `RelationalEntityStore.listEntitiesByRelation`, which runs **one indexed SQL join** per call (`JDBCBackend.listEntitiesByRelation`). Its callers are all metadata governance managers:
+
+| Caller | Relation | API that uses it |
+| -------------------- | ---------------------------- |-----------------------------------|
+| `OwnerManager` | `OWNER_REL` | `GET .../owner` |
+| `RoleManager` | role relations | role / authorization management |
+| `FutureGrantManager` | role/user/group relations | applying future grants (admin op) |
+| `TagManager` | `TAG_METADATA_OBJECT_REL` | tag endpoints |
+| `PolicyManager` | `POLICY_METADATA_OBJECT_REL` | policy endpoints |
+
+**Who does not.** The two paths that must be fast do **not** use it:
+
+- **Core metadata reads** (`get` / `list` of table, schema, catalog, …) never call `listEntitiesByRelation`. Removing the relation cache does not affect them at all.
+- **Authorization checks** (`JcasbinAuthorizer`) read roles straight from mappers (`RoleMetaMapper.listRolesByUserId` / `listRolesByGroupId`), owner from its own `ownerRelCache` (which polls `owner_meta`), and id from its own `metadataIdCache`. It does not use the entity store relation cache at all. Relation caching was first added with authorization in mind, but authorization no longer uses it.
+
+**Cost of removing it.** Each call becomes one indexed query — not an N+1 (one query per item). No list endpoint loads relations per item in a loop. The one place a single request makes several queries is **tag / policy inheritance**: listing an object's tags also reads its parents (the object plus up to ~3 ancestors), so a tag lookup is up to ~4 single-row queries; the cache mainly saves re-reading popular parents. This is the only workload where removing the cache adds real DB load, and it can be measured today — those calls are already `@Monitored` (`baseMetricName = "listTagsForMetadataObject"`, `"getOwner"`, `"listPoliciesForMetadataObject"`).
+
+**Decision.** Remove relation caching from the entity store cache. Relation reads go straight to the DB (one indexed query each), the same as authorization already does. This is safe for the core read path and for authorization; the only risk is workloads with heavy tag/policy inheritance reads, which we can watch with the existing metrics and, if ever needed, address by adding precise relation caching back later.
+
+The result: the cache holds only **entity keys**, so cross-node invalidation becomes the easy one-to-one case, and (as both implementations show) each design loses its hardest part. The `ReverseIndexCache` and the two-direction relation keys are removed with it.
+
+But "cache only entity keys" is not the end of it: some entities **copy fields from other entities**, which would bring the reverse-lookup problem back. The next section works out which entities are actually safe to cache.
+
+---
+
+## Which Entities to Cache
+
+Dropping relations leaves the entity keys. But not every entity key is truly one-to-one. Some entities store fields **copied from other entities**, and those copies go stale when the other entity changes — which brings back the same reverse lookup we just removed. So we look at what each cached entity actually holds.
+
+**Self-contained vs. derived.**
+
+| Entity | Copies a field from another entity? | Safe to cache on its own? |
+| ------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------- |
+| metalake, catalog, schema, table, topic, model, view, fileset | no — holds only its own data (columns, properties, comment…) | yes |
+| tag, policy | no — associations are relations, not stored on the entity | yes |
+| user, group | yes — `roleNames` / `roleIds`, built from the user's roles | no |
+| role | yes — `securableObjects`, built from metadata objects | no |
+
+**Why user / group / role are a problem.**
+
+- `getUserByIdentifier` builds `roleNames` at read time by joining the user's roles (`UserMetaService` calls `RoleMetaService.listRolesByUserId`). If a role is dropped, it disappears from every user's list, but the user rows are not touched — so a cached user still lists the dropped role. Finding which users hold a role is a reverse lookup (role → users), exactly what dropping relations was meant to avoid.
+- `RoleEntity.securableObjects` has the same shape one level up: if a metadata object is renamed or dropped, a cached role that points at it is stale, and finding which roles point at an object is again a reverse lookup (object → roles).
+
+**Does authorization need these in the cache?** This is the key question, because authorization is the hot path. We checked `JcasbinAuthorizer`:
+
+- **user / group — no.** It reads user and group data through its own mappers (`UserMetaMapper`, `GroupMetaMapper`) into its own caches (`userRoleCache`, `groupRoleCache`), never through the entity store cache. So excluding user/group from the entity store cache does not affect authorization at all.
+- **role — only at cold start or after a change.** It does read role entities through the entity store (`entityStore.batchGet/get(ROLE)`), but only to (re)load a role's policies into the enforcer. Loaded roles are held in `loadedRoles`, a cache with `expireAfterAccess` (default 1 hour), so a role used at least once an hour never expires and the entity read is skipped. The entity read happens only on cold start, right after a role is edited, or after a role sits unused for over an hour — each a cheap one-time `batchGet`, not a per-request cost.
+
+So caching user, group, and role buys almost nothing (authorization does not depend on it) and costs a lot (the reverse-lookup problem comes back). tag and policy are safe to cache, but they are low-volume governance objects, not the read-heavy metadata the cache exists for.
+
+**Conclusion: cache only the basic metadata objects** — metalake, catalog, schema, table, topic, model, view, fileset. In code this is a small allowlist of entity types in the cache. Every cached entity is then self-contained and one-to-one, so cross-node invalidation stays precise with no reverse lookups. As a bonus, these entities already write ALTER/DROP rows to `entity_change_log`, so the writer side needs no change at all.
+
+The cache now holds only self-contained metadata objects. The next question is how to tell the other nodes to drop a key when it changes.
+
+---
+
+## Approaches to Multi-Node Consistency
+
+Keeping a per-node cache fresh across a cluster is a common problem: after a write on one node, no other node may serve stale data. The standard techniques:
+
+| Approach | How it works | Trade-off |
+| -------------------------- | ------------------------------------------------------------------------------------------- |------------------------------------------------------------------------------------|
+| TTL only | each entry expires after a fixed time | no work, but every node serves old data until the TTL passes |
+| Pub/sub broadcast | the writer sends "invalidate X"; every node subscribes | low delay, but needs a message bus and must handle missed messages |
+| Change-log table + poller | the writer records the change in a DB table in the same transaction; each node polls it | no new infrastructure (reuses the DB), survives restarts; up to one poll of delay |
+| Shared (distributed) cache | one copy for the whole cluster, so there is nothing per-node to keep fresh | no propagation at all, but needs Redis/Memcached and a network round-trip per read |
+
+### How other metadata systems solve it
+
+We looked at how similar systems keep **their own per-node cache** coherent across a cluster (not how they notify downstream/derived systems — that is a different problem). **The most common answer is a per-node cache kept fresh by polling or by an invalidation/broadcast signal; no one relies on plain TTL.** Each row below has a source:
+
+| System | How it keeps its per-node cache fresh across nodes | Technique |
+| ---------------------------------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------|
+| **Hive Metastore** (`CachedStore`) | each node's in-memory cache is updated by a background thread that **polls the `NOTIFICATION_LOG` table** (written by `DbNotificationListener`); the log is in commit order and is the source of truth, and reads fall back to the DB until the thread catches up [1][2] | change-log + poll |
+| **Apache Ranger** (plugins) | each plugin keeps a **local policy cache** and **periodically polls Ranger Admin** for a newer version (default every 30s, `policy.pollIntervalMs`), downloading only the delta when the version changes [3] | periodic poll |
+| **Confluent Schema Registry** | one compacted Kafka topic **`_schemas`** is the commit log and the source of truth; every node reads it in a background thread to build its **local materialized view** [4] | shared log |
+| **Apache Impala** (`catalogd`) | metadata changes are **broadcast to all coordinators through `statestored`**; in local-catalog mode coordinators instead **fetch on demand and cache locally**, and invalidate that cache on `catalogd` failover [5] | broadcast / on-demand pull |
+| **Redis** (client-side caching) | with `CLIENT TRACKING` the server remembers which keys each client cached and **pushes an invalidation message** (RESP3 push) when a key changes, so the client flushes its local copy [6] | server-push invalidation |
+| **CockroachDB** | each node caches table/schema descriptors under a **versioned lease**; at most the **two latest versions** can be leased at once, and a schema change waits for old leases to be released or to expire (lease duration on the order of minutes) before advancing [7] | versioned lease |
+| **Trino** (Hive connector) | a coordinator-side metastore cache with a fixed **TTL plus background refresh** (`hive.metastore-cache-ttl`, `hive.metastore-refresh-interval`); its own docs note this can return stale data [8] | TTL + refresh |
+
+Two things stand out: **polling a change/version log (Hive, Ranger) is the most common, no-new-infrastructure answer**, and the one system that relies on **TTL alone (Trino) is documented to sometimes return stale data** — even CockroachDB, which looks TTL-like, actually uses bounded leases with active release, not plain expiry. That is exactly why TTL is not enough for us.
+
+### The two approaches we pick
+
+The closest match to what Gravitino needs is **Hive Metastore's `CachedStore`**: a per-node cache kept fresh by polling a change log in the same DB. Gravitino already has both pieces — the DB as the source of truth, and an `entity_change_log` table with a poller (built for the jcasbin cache). So this works with **no new infrastructure**. This is the default, and we call it `caffeine`.
+
+The broadcast / pub-sub-invalidation systems (Impala's `statestored`, Redis client-side caching, Schema Registry's shared log) work well, but they need a **message bus that Gravitino does not have**, so pub/sub is left for later (see the [roadmap](#roadmap)). **TTL alone** (Trino) is rejected for the stale-read reason its own docs give. That leaves two approaches that need no new component:
+
+- **reuse the DB** — a per-node cache kept fresh by the change log. → `caffeine`
+- **use a shared copy** — for teams already running Redis and wanting strong consistency, keep one copy in Redis. → `redis`
+
+**Sources**
+
+1. Hive — *Synchronized Metastore Cache*: <https://cwiki.apache.org/confluence/display/Hive/Synchronized+Metastore+Cache> (and HIVE-18661: <https://issues.apache.org/jira/browse/HIVE-18661>)
+2. Hive — `CachedStore.java` / `DbNotificationListener.java`: <https://github.com/apache/hive/blob/master/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/cache/CachedStore.java>
+3. Apache Ranger — *FAQ* (plugins cache policies locally and poll Ranger Admin at intervals): <https://ranger.apache.org/faq.html>; default `pollIntervalMs = 30000` in the plugin config: <https://github.com/apache/ranger/blob/master/hive-agent/conf/ranger-hive-security.xml>
+4. Confluent Schema Registry docs: <https://docs.confluent.io/platform/current/schema-registry/index.html>
+5. Apache Impala — *Metadata Management* (catalogd broadcasts via statestored; local-catalog mode fetches on demand and caches): <https://impala.apache.org/docs/build/html/topics/impala_metadata.html>
+6. Redis — *Client-side caching* / `CLIENT TRACKING` (RESP3 push invalidation): <https://redis.io/docs/latest/develop/reference/client-side-caching/>
+7. CockroachDB — *Table Descriptor Lease* RFC (at most two leased versions; ~5m lease): <https://github.com/cockroachdb/cockroach/blob/master/docs/RFCS/20151009_table_descriptor_lease.md> (and *Online Schema Changes*: <https://www.cockroachlabs.com/docs/stable/online-schema-changes>)
+8. Trino — *Metastores* docs: <https://trino.io/docs/current/object-storage/metastores.html> (stale-read note: <https://github.com/trinodb/trino/issues/10512>)
+
+---
+
+## The Pluggable Framework
+
+We now have two approaches that behave differently — one keeps a local copy per node, the other keeps one shared copy. To let a user pick either one by config, the cache stays **pluggable**, and each implementation says which kind it is. The `EntityCache` SPI adds one method:
+
+```
+EntityCache.coherence() → LOCAL_PER_NODE | SHARED
+```
+
+- `LOCAL_PER_NODE` — each node has its own copy, so a write must be **sent to the other nodes** to clear their copies. `caffeine` is this kind.
+- `SHARED` — one copy for the whole cluster, so a write clears it once and every node sees it. Nothing to send. `redis` is this kind.
+
+The write path is the same for both; only what happens after the local clear differs, and that is decided by `coherence()`:
+
+<!-- diagram source: diagrams/coherence-gate.mmd (regenerate with mermaid-cli) -->
+
+
+`CacheFactory.ENTITY_CACHES` is already a name → class table loaded by reflection, so adding `redis` next to `caffeine` is one new table entry with no change to the callers.
+
+The rest of this document describes each implementation — first the default local cache, then the shared cache.
+
+---
+
+# Implementation A — Caffeine (`caffeine`, `LOCAL_PER_NODE`, default)
+
+With only self-contained metadata objects cached, "entity X changed" names exactly the key to drop, and **any node can drop it** — no reverse key, no fan-out. The channel to carry "entity X changed" to the other nodes already exists and is already used by other caches.
+
+<!-- diagram source: diagrams/entity-key-invalidation.mmd (regenerate with mermaid-cli) -->
+
+
+### Reuse the existing transport
+
+`entity_change_log` and `EntityChangeLogPoller` already exist and are already used by two consumers:
+
+- `CatalogChangeLogListener` → clears `CatalogManager`'s catalog cache;
+- `JcasbinChangeListener` → clears jcasbin's **id-mapping cache** (`metadataIdCache`).
+
+Each row is `{metalake, entity_type, full_name, operate_type (ALTER | DROP), created_at}`. The structural MetaServices (metalake, catalog, schema, table, topic, model, view, fileset) already write a row on ALTER/DROP. We add the entity store cache as a **third consumer** of the same poller.
+
+### Writer side
+
+The cache now holds only metadata objects, and those **already write** an ALTER/DROP row to `entity_change_log` today. So the writer side needs **no change** — no new rows, no new columns, no new operate type:
+
+| Change | Cached? | Writes a change-log row |
+| ----------------------------------------------------- | ------- | ----------------------- |
+| structural ALTER/DROP (table, schema, catalog, …) | yes | yes — already emitted |
+| user / group / role / tag / policy ALTER/DROP | no | not needed (not cached) |
+| relation change (grant, set owner, attach tag/policy) | no | not needed (not cached) |
+
+The existing structural rows are written in the same transaction as the entity write, so nothing new is added here.
+
+### Reader side
+
+A new `EntityChangeLogListener` for the entity store cache runs on the **same poller** and replays each row as a direct invalidation:
+
+```
+onEntityChange(rows):
+ for row in rows:
+ cache.invalidate(identOf(row), row.entity_type) # drop exactly this entity key
+```
+
+Dropping a container (for example a schema) must also drop its cached children. That uses the **forward** prefix scan the cache already has (`cacheIndex`), on the local node — the reverse index is not involved. This is the only remaining cascade.
+
+### A third consumer of the existing feed
+
+The entity store cache becomes a third consumer of the poller, next to the catalog cache and the jcasbin id-mapping cache. All three read the same structural ALTER/DROP rows that already exist — the entity store cache clears its entity key, the catalog cache clears its catalog, jcasbin clears its id mapping. There is no new row type, so the existing consumers do not change.
+
+### Consistency
+
+The cache is never the source of truth. The write path always reads the DB under the optimistic version lock, so eventual consistency can **never** cause a lost update or corrupt data. Its only observable effect is **bounded read staleness on non-writing nodes**: for up to one poll interval, a node other than the writer may serve an older value.
+
+- **Other nodes:** eventual — an entity key is dropped within one poll interval of the change.
+- **Writing node:** unchanged — it still clears its own cache on the write path, so it reads its own writes right away. Its own row is replayed later, which does nothing (clearing an already-clear key is a no-op).
+- **Write path:** unchanged — it reads the DB with the optimistic version check.
+
+The rest of this section works through every way that staleness window can be observed, and how each is handled.
+
+#### Staleness scenarios and mitigations
+
+**1. Plain stale read (bounded, mostly tolerable).**
+
+| # | Scenario | Effect | Possible mitigation |
+| - | -------------------------------------------------------------- |-----------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------|
+| 1 | Node A ALTERs a table (add column); B GETs it | B serves the old schema for up to one poll interval | Accept within the SLA window; a caller that needs an exact schema uses a consistent (cache-bypass) read |
+| 2 | Node A DROPs a table; B GETs it | B still reports it as present (cache hit) until the next poll | Accept — any write to it on B is re-validated against the DB and rejected as not-found, so no corruption |
+| 3 | RENAME (the old name behaves like a DROP); B GETs the old name | B keeps resolving the old name until the next poll; the new name misses → DB load | Same as DROP — bounded by the poll interval |
+| 4 | A property changes (e.g. Iceberg metadata-location); B GETs it | B returns the old location → a query on B may read an old snapshot/path | Highest-value case: offer a consistent (cache-bypass) read for location-sensitive callers, or use `redis` |
Review Comment:
If Iceberg supports changing the metadata location, this is really a big problem.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3551978660
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -0,0 +1,350 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+---
+title: "Multi-Node Support for the Entity Store Cache"
+status: "Draft"
+date: "2026-07-07"
+---
+
+## Background
+
+Gravitino has two caches:
+
+- The **jcasbin authorization cache** already works with more than one node.
+- The **entity store cache** does not. When a change happens on node A, only node A clears its cache. Node B keeps serving the old data until its entry expires.
+
+Because of this, the only safe way to run more than one node today is to turn the entity store cache off (`gravitino.cache.enabled=false`). That is bad for read-heavy catalogs, especially Iceberg.
+
+This document proposes a design to make the entity store cache correct when running more than one node. It is a design proposal; no behavior has changed yet.
+
+## Goals and Non-Goals
+
+**Goals**
+
+- Make the entity store cache correct with more than one node, so `gravitino.cache.enabled=true` is safe.
+- Keep the cache **pluggable**: one SPI, chosen by `gravitino.cache.impl`. Ship `caffeine` as the default (no extra dependency) and `redis` as an option the user turns on by config.
+- Keep single-node behavior and the write path (the optimistic version lock) unchanged.
+
+**Non-Goals**
+
+- Replace the entity store or its write path. The cache sits in front of the store and is never the source of truth.
+- Add a cluster membership / gossip layer or any other complex distributed system. We only use the DB Gravitino already needs, or the external cache the user turns on.
+
+---
+
+## Current Cache Implementation
+
+`EntityCache` is already an SPI, chosen by `gravitino.cache.impl` and created by `CacheFactory`. There is one implementation today, `CaffeineEntityCache` (`caffeine`): an in-memory cache, **one copy per node**, with two kinds of entries:
+
+- **entity keys** `(ident, type)` → the entity itself;
+- **relation keys** `(ident, type, relType)` → the list of related entities, stored **in both directions** and kept in step by an in-process **reverse index** (`ReverseIndexCache`).
+
+On a write, the node clears the changed key and then uses the reverse index to clear the related keys. On a single node this is correct. The problem is that this clearing happens **only on the node that made the change** (`RelationalEntityStore` calls `cache.invalidate(...)` locally). Nothing tells the other nodes, so they serve old data until their entries expire.
+
+Some behavior is already safe with more than one node and does not change:
+
+| Already correct | Why |
+| ------------------------- | ---------------------------------------------------------------------------- |
+| Writes never lose updates | The write path reads the DB (not the cache) with an optimistic version check |
+| `list(namespace)` | Skips the cache, so it is never stale |
+| CREATE | Needs nothing: no negative caching, and `list` skips the cache |
+
+The rest of the problem splits in two:
+
+- **entity keys** are one-to-one. "table T changed" names exactly the key to drop, and any node can drop it. This is easy.
+- **relation keys** have a reverse key. Dropping one side (say a role) also means dropping the other side's key (each user that had the role), but "the role changed" does not say *which* users those are. The writing node knows them from its local reverse index; a remote node may not.
+
+That reverse key is the hard part. So the first question is whether the cache needs relations at all.
+
+---
+
+## Do We Need to Cache Relations?
+
+All the cross-node difficulty comes from relation caching (the reverse key and the write fan-out). Before building around it, we checked whether it is actually important for performance. It is not.
+
+**Who reads the relation cache.** The cached relation path is `RelationalEntityStore.listEntitiesByRelation`, which runs **one indexed SQL join** per call (`JDBCBackend.listEntitiesByRelation`). Its callers are all metadata governance managers:
+
+| Caller | Relation | API that uses it |
+| -------------------- | ---------------------------- |-----------------------------------|
+| `OwnerManager` | `OWNER_REL` | `GET .../owner` |
+| `RoleManager` | role relations | role / authorization management |
+| `FutureGrantManager` | role/user/group relations | applying future grants (admin op) |
+| `TagManager` | `TAG_METADATA_OBJECT_REL` | tag endpoints |
+| `PolicyManager` | `POLICY_METADATA_OBJECT_REL` | policy endpoints |
+
+**Who does not.** The two paths that must be fast do **not** use it:
+
+- **Core metadata reads** (`get` / `list` of table, schema, catalog, …) never call `listEntitiesByRelation`. Removing the relation cache does not affect them at all.
+- **Authorization checks** (`JcasbinAuthorizer`) read roles straight from mappers (`RoleMetaMapper.listRolesByUserId` / `listRolesByGroupId`), owner from its own `ownerRelCache` (which polls `owner_meta`), and id from its own `metadataIdCache`. It does not use the entity store relation cache at all. Relation caching was first added with authorization in mind, but authorization no longer uses it.
+
+**Cost of removing it.** Each call becomes one indexed query — not an N+1 (one query per item). No list endpoint loads relations per item in a loop. The one place a single request makes several queries is **tag / policy inheritance**: listing an object's tags also reads its parents (the object plus up to ~3 ancestors), so a tag lookup is up to ~4 single-row queries; the cache mainly saves re-reading popular parents. This is the only workload where removing the cache adds real DB load, and it can be measured today — those calls are already `@Monitored` (`baseMetricName = "listTagsForMetadataObject"`, `"getOwner"`, `"listPoliciesForMetadataObject"`).
+
+**Decision.** Remove relation caching from the entity store cache. Relation reads go straight to the DB (one indexed query each), the same as authorization already does. This is safe for the core read path and for authorization; the only risk is workloads with heavy tag/policy inheritance reads, which we can watch with the existing metrics and, if ever needed, address by adding precise relation caching back later.
+
+The result: the cache holds only **entity keys**, so cross-node invalidation becomes the easy one-to-one case, and (as both implementations show) each design loses its hardest part. The `ReverseIndexCache` and the two-direction relation keys are removed with it.
+
+But "cache only entity keys" is not the end of it: some entities **copy fields from other entities**, which would bring the reverse-lookup problem back. The next section works out which entities are actually safe to cache.
+
+---
+
+## Which Entities to Cache
+
+Dropping relations leaves the entity keys. But not every entity key is truly one-to-one. Some entities store fields **copied from other entities**, and those copies go stale when the other entity changes — which brings back the same reverse lookup we just removed. So we look at what each cached entity actually holds.
+
+**Self-contained vs. derived.**
+
+| Entity | Copies a field from another entity? | Safe to cache on its own? |
+| ------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------- |
+| metalake, catalog, schema, table, topic, model, view, fileset | no — holds only its own data (columns, properties, comment…) | yes |
+| tag, policy | no — associations are relations, not stored on the entity | yes |
+| user, group | yes — `roleNames` / `roleIds`, built from the user's roles | no |
+| role | yes — `securableObjects`, built from metadata objects | no |
+
+**Why user / group / role are a problem.**
+
+- `getUserByIdentifier` builds `roleNames` at read time by joining the user's roles (`UserMetaService` calls `RoleMetaService.listRolesByUserId`). If a role is dropped, it disappears from every user's list, but the user rows are not touched — so a cached user still lists the dropped role. Finding which users hold a role is a reverse lookup (role → users), exactly what dropping relations was meant to avoid.
+- `RoleEntity.securableObjects` has the same shape one level up: if a metadata object is renamed or dropped, a cached role that points at it is stale, and finding which roles point at an object is again a reverse lookup (object → roles).
+
+**Does authorization need these in the cache?** This is the key question, because authorization is the hot path. We checked `JcasbinAuthorizer`:
+
+- **user / group — no.** It reads user and group data through its own mappers (`UserMetaMapper`, `GroupMetaMapper`) into its own caches (`userRoleCache`, `groupRoleCache`), never through the entity store cache. So excluding user/group from the entity store cache does not affect authorization at all.
+- **role — only at cold start or after a change.** It does read role entities through the entity store (`entityStore.batchGet/get(ROLE)`), but only to (re)load a role's policies into the enforcer. Loaded roles are held in `loadedRoles`, a cache with `expireAfterAccess` (default 1 hour), so a role used at least once an hour never expires and the entity read is skipped. The entity read happens only on cold start, right after a role is edited, or after a role sits unused for over an hour — each a cheap one-time `batchGet`, not a per-request cost.
+
+So caching user, group, and role buys almost nothing (authorization does not depend on it) and costs a lot (the reverse-lookup problem comes back). tag and policy are safe to cache, but they are low-volume governance objects, not the read-heavy metadata the cache exists for.
+
+**Conclusion: cache only the basic metadata objects** — metalake, catalog, schema, table, topic, model, view, fileset. In code this is a small allowlist of entity types in the cache. Every cached entity is then self-contained and one-to-one, so cross-node invalidation stays precise with no reverse lookups. As a bonus, these entities already write ALTER/DROP rows to `entity_change_log`, so the writer side needs no change at all.
Review Comment:
Function and review should both be added.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3543922764
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -0,0 +1,350 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+---
+title: "Multi-Node Support for the Entity Store Cache"
+status: "Draft"
+date: "2026-07-07"
+---
+
+## Background
+
+Gravitino has two caches:
+
+- The **jcasbin authorization cache** already works with more than one node.
+- The **entity store cache** does not. When a change happens on node A, only node A clears its cache. Node B keeps serving the old data until its entry expires.
+
+Because of this, the only safe way to run more than one node today is to turn the entity store cache off (`gravitino.cache.enabled=false`). That is bad for read-heavy catalogs, especially Iceberg.
+
+This document proposes a design to make the entity store cache correct when running more than one node. It is a design proposal; no behavior has changed yet.
+
+## Goals and Non-Goals
+
+**Goals**
+
+- Make the entity store cache correct with more than one node, so `gravitino.cache.enabled=true` is safe.
+- Keep the cache **pluggable**: one SPI, chosen by `gravitino.cache.impl`. Ship `caffeine` as the default (no extra dependency) and `redis` as an option the user turns on by config.
+- Keep single-node behavior and the write path (the optimistic version lock) unchanged.
+
+**Non-Goals**
+
+- Replace the entity store or its write path. The cache sits in front of the store and is never the source of truth.
+- Add a cluster membership / gossip layer or any other complex distributed system. We only use the DB Gravitino already needs, or the external cache the user turns on.
+
+---
+
+## Current Cache Implementation
+
+`EntityCache` is already an SPI, chosen by `gravitino.cache.impl` and created by `CacheFactory`. There is one implementation today, `CaffeineEntityCache` (`caffeine`): an in-memory cache, **one copy per node**, with two kinds of entries:
+
+- **entity keys** `(ident, type)` → the entity itself;
+- **relation keys** `(ident, type, relType)` → the list of related entities, stored **in both directions** and kept in step by an in-process **reverse index** (`ReverseIndexCache`).
+
+On a write, the node clears the changed key and then uses the reverse index to clear the related keys. On a single node this is correct. The problem is that this clearing happens **only on the node that made the change** (`RelationalEntityStore` calls `cache.invalidate(...)` locally). Nothing tells the other nodes, so they serve old data until their entries expire.
+
+Some behavior is already safe with more than one node and does not change:
+
+| Already correct | Why |
+| ------------------------- | ---------------------------------------------------------------------------- |
+| Writes never lose updates | The write path reads the DB (not the cache) with an optimistic version check |
+| `list(namespace)` | Skips the cache, so it is never stale |
+| CREATE | Needs nothing: no negative caching, and `list` skips the cache |
+
+The rest of the problem splits in two:
+
+- **entity keys** are one-to-one. "table T changed" names exactly the key to drop, and any node can drop it. This is easy.
+- **relation keys** have a reverse key. Dropping one side (say a role) also means dropping the other side's key (each user that had the role), but "the role changed" does not say *which* users those are. The writing node knows them from its local reverse index; a remote node may not.
+
+That reverse key is the hard part. So the first question is whether the cache needs relations at all.
+
+---
+
+## Do We Need to Cache Relations?
+
+All the cross-node difficulty comes from relation caching (the reverse key and the write fan-out). Before building around it, we checked whether it is actually important for performance. It is not.
+
+**Who reads the relation cache.** The cached relation path is `RelationalEntityStore.listEntitiesByRelation`, which runs **one indexed SQL join** per call (`JDBCBackend.listEntitiesByRelation`). Its callers are all metadata governance managers:
+
+| Caller | Relation | API that uses it |
+| -------------------- | ---------------------------- |-----------------------------------|
+| `OwnerManager` | `OWNER_REL` | `GET .../owner` |
+| `RoleManager` | role relations | role / authorization management |
+| `FutureGrantManager` | role/user/group relations | applying future grants (admin op) |
+| `TagManager` | `TAG_METADATA_OBJECT_REL` | tag endpoints |
+| `PolicyManager` | `POLICY_METADATA_OBJECT_REL` | policy endpoints |
+
+**Who does not.** The two paths that must be fast do **not** use it:
+
+- **Core metadata reads** (`get` / `list` of table, schema, catalog, …) never call `listEntitiesByRelation`. Removing the relation cache does not affect them at all.
+- **Authorization checks** (`JcasbinAuthorizer`) read roles straight from mappers (`RoleMetaMapper.listRolesByUserId` / `listRolesByGroupId`), owner from its own `ownerRelCache` (which polls `owner_meta`), and id from its own `metadataIdCache`. It does not use the entity store relation cache at all. Relation caching was first added with authorization in mind, but authorization no longer uses it.
+
+**Cost of removing it.** Each call becomes one indexed query — not an N+1 (one query per item). No list endpoint loads relations per item in a loop. The one place a single request makes several queries is **tag / policy inheritance**: listing an object's tags also reads its parents (the object plus up to ~3 ancestors), so a tag lookup is up to ~4 single-row queries; the cache mainly saves re-reading popular parents. This is the only workload where removing the cache adds real DB load, and it can be measured today — those calls are already `@Monitored` (`baseMetricName = "listTagsForMetadataObject"`, `"getOwner"`, `"listPoliciesForMetadataObject"`).
+
+**Decision.** Remove relation caching from the entity store cache. Relation reads go straight to the DB (one indexed query each), the same as authorization already does. This is safe for the core read path and for authorization; the only risk is workloads with heavy tag/policy inheritance reads, which we can watch with the existing metrics and, if ever needed, address by adding precise relation caching back later.
+
+The result: the cache holds only **entity keys**, so cross-node invalidation becomes the easy one-to-one case, and (as both implementations show) each design loses its hardest part. The `ReverseIndexCache` and the two-direction relation keys are removed with it.
+
+But "cache only entity keys" is not the end of it: some entities **copy fields from other entities**, which would bring the reverse-lookup problem back. The next section works out which entities are actually safe to cache.
+
+---
+
+## Which Entities to Cache
+
+Dropping relations leaves the entity keys. But not every entity key is truly one-to-one. Some entities store fields **copied from other entities**, and those copies go stale when the other entity changes — which brings back the same reverse lookup we just removed. So we look at what each cached entity actually holds.
+
+**Self-contained vs. derived.**
+
+| Entity | Copies a field from another entity? | Safe to cache on its own? |
+| ------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------- |
+| metalake, catalog, schema, table, topic, model, view, fileset | no — holds only its own data (columns, properties, comment…) | yes |
+| tag, policy | no — associations are relations, not stored on the entity | yes |
+| user, group | yes — `roleNames` / `roleIds`, built from the user's roles | no |
+| role | yes — `securableObjects`, built from metadata objects | no |
+
+**Why user / group / role are a problem.**
+
+- `getUserByIdentifier` builds `roleNames` at read time by joining the user's roles (`UserMetaService` calls `RoleMetaService.listRolesByUserId`). If a role is dropped, it disappears from every user's list, but the user rows are not touched — so a cached user still lists the dropped role. Finding which users hold a role is a reverse lookup (role → users), exactly what dropping relations was meant to avoid.
+- `RoleEntity.securableObjects` has the same shape one level up: if a metadata object is renamed or dropped, a cached role that points at it is stale, and finding which roles point at an object is again a reverse lookup (object → roles).
+
+**Does authorization need these in the cache?** This is the key question, because authorization is the hot path. We checked `JcasbinAuthorizer`:
+
+- **user / group — no.** It reads user and group data through its own mappers (`UserMetaMapper`, `GroupMetaMapper`) into its own caches (`userRoleCache`, `groupRoleCache`), never through the entity store cache. So excluding user/group from the entity store cache does not affect authorization at all.
+- **role — only at cold start or after a change.** It does read role entities through the entity store (`entityStore.batchGet/get(ROLE)`), but only to (re)load a role's policies into the enforcer. Loaded roles are held in `loadedRoles`, a cache with `expireAfterAccess` (default 1 hour), so a role used at least once an hour never expires and the entity read is skipped. The entity read happens only on cold start, right after a role is edited, or after a role sits unused for over an hour — each a cheap one-time `batchGet`, not a per-request cost.
+
+So caching user, group, and role buys almost nothing (authorization does not depend on it) and costs a lot (the reverse-lookup problem comes back). tag and policy are safe to cache, but they are low-volume governance objects, not the read-heavy metadata the cache exists for.
+
+**Conclusion: cache only the basic metadata objects** — metalake, catalog, schema, table, topic, model, view, fileset. In code this is a small allowlist of entity types in the cache. Every cached entity is then self-contained and one-to-one, so cross-node invalidation stays precise with no reverse lookups. As a bonus, these entities already write ALTER/DROP rows to `entity_change_log`, so the writer side needs no change at all.
Review Comment:
Should you consider function?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "roryqi (via GitHub)" <gi...@apache.org>.
roryqi commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3613910578
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -252,54 +254,68 @@ The entity store cache becomes a third consumer of the poller, next to the catal
### Consistency
-The cache is never the source of truth. The write path always reads the DB under the optimistic version lock, so eventual consistency can **never** cause a lost update or corrupt data. Its only observable effect is **bounded read staleness on non-writing nodes**: for up to one poll interval, a node other than the writer may serve an older value.
+The cache never holds the truth. Every write goes to the DB first, under the version lock, so a stale cache can **never** cause a lost update or a bad write. The only thing that can go wrong is that a read on **another node** returns an old value for a short time — at most one poll interval, until that node drops the key.
-- **Other nodes:** eventual — an entity key is dropped within one poll interval of the change.
-- **Writing node:** unchanged — it still clears its own cache on the write path, so it reads its own writes right away. Its own row is replayed later, which does nothing (clearing an already-clear key is a no-op).
-- **Write path:** unchanged — it reads the DB with the optimistic version check.
+So the real question is simple: when another node reads an old value, does it matter? We went through every alter and every drop, for every cached entity, one at a time. A stale read falls into one of two buckets:
-The rest of this section works through every way that staleness window can be observed, and how each is handled.
+- **The old value makes the next step fail with an error.** The user sees the error and tries again. This is safe.
+- **The old value is used silently and gives a wrong answer, with no error.** This is the dangerous kind.
-#### Staleness scenarios and mitigations
+We only need to worry about the second bucket.
-**1. Plain stale read (bounded, mostly tolerable).**
+#### Two groups of cached entities
-| # | Scenario | Effect | Possible mitigation |
-| - | -------------------------------------------------------------- |-----------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------|
-| 1 | Node A ALTERs a table (add column); B GETs it | B serves the old schema for up to one poll interval | Accept within the SLA window; a caller that needs an exact schema uses a consistent (cache-bypass) read |
-| 2 | Node A DROPs a table; B GETs it | B still reports it as present (cache hit) until the next poll | Accept — any write to it on B is re-validated against the DB and rejected as not-found, so no corruption |
-| 3 | RENAME (the old name behaves like a DROP); B GETs the old name | B keeps resolving the old name until the next poll; the new name misses → DB load | Same as DROP — bounded by the poll interval |
-| 4 | A property changes (e.g. Iceberg metadata-location); B GETs it | B returns the old location → a query on B may read an old snapshot/path | Highest-value case: offer a consistent (cache-bypass) read for location-sensitive callers, or use `redis` |
+The danger depends on where the real data comes from.
-**2. Read-your-writes across nodes.**
+**Group 1 — the data comes from the connector: table, view, topic, and schemas in external catalogs.** For these, Gravitino does not read the metadata from its own cache. On every load it asks the underlying system (Hive, Iceberg, JDBC, Kafka) for the current object, and uses the cached entity only for Gravitino's own id and audit fields. All nodes ask the same underlying system, so they all see the same thing. If the object was dropped or renamed, the connector call fails right away with a "not found" error. **This whole group is safe — nothing to do.**
-| # | Scenario | Effect | Possible mitigation |
-| - |---------------------------------------------------------------------|-------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
-| 5 | Through a load balancer, ALTER on A then an immediate read on B | Stale — violates session consistency; without sticky routing the change looks lost | Sticky sessions at the LB, or a client-supplied last-seen version that bypasses the cache when the copy is older; `redis` removes it entirely |
-| 6 | CREATE (rather than ALTER/DROP) | No problem — no negative caching and `list` skips the cache, so a new entity is visible at once | None needed |
+**Group 2 — the data comes from Gravitino's own store: metalake, catalog, managed schema, fileset, model, model version, function.** Here the cached entity *is* the answer, so a stale read really can return an old value. We looked at each alter in this group.
-**3. Cross-node read-modify-write.**
+(Views follow the same rule as tables: their definition is read through the connector on every load, so they sit in Group 1 and are safe.)
-| # | Scenario | Effect | Possible mitigation |
-| - | ------------------------------------------------------------------------------------- |-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------|
-| 7 | B reads stale value A and submits an update carrying A's version as the expected one | The optimistic lock rejects it on version mismatch — safe, but the user sees an unexpected conflict | Accept (correctness is preserved); reduce its frequency with the read-your-writes mitigations above |
+#### Walking through the alters in Group 2
-**4. Is the window actually bounded? — poller reliability (the real risk).** The "at most one poll interval" guarantee holds **only if the poller never drops a row**. If it does, the stale entry survives until the cache TTL, so this is the one place eventual consistency itself can break.
+Most alters are safe:
-| # | Scenario | Effect | Possible mitigation |
-| -- |-----------------------------------------------------------------------------------------------------------|-----------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------|
-| 8 | Commit-ordering gap / a skipped row | The key is never invalidated; stale until the TTL | Reuse the lag-safe, id-based polling already built for the change log (`#11736`); keep the cache TTL as a backstop |
-| 9 | Poller thread dies / DB briefly unreachable | That node serves stale data until the TTL | TTL backstop + monitor poller liveness/lag and alert |
-| 10 | Hierarchical DROP: only the container (schema) emits a row; children are cleared by a forward prefix scan | Correct as long as the prefix scan covers every child key | Cover with the hierarchical-drop test; confirm no child is written in a separate transaction that outlives the container row |
+| Change | What a stale read does | Safe? |
+| -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
+| rename (metalake, catalog, schema, fileset, model) | reading the old name returns a leftover copy, but any write to it goes to the DB and fails; the new name misses the cache and loads fresh from the DB | yes |
+| update comment | you see an old comment for a moment | yes |
+| set / remove property (metalake, model, fileset) | these properties do not change where the data lives | yes |
+| fileset storage location | **cannot be changed** — there is no alter for it, so it can never go stale | yes |
+| drop | for Group 1 the connector call fails; for a fileset the file path is gone and access fails | yes |
+| catalog changes | already handled today by a separate cross-node signal (`CatalogChangeLogListener`), not by this cache | yes |
-**5. Idempotency (no issue).** Replaying ALTER then DROP, in any order or duplicated, is safe: invalidation is idempotent, so out-of-order or repeated replay has no effect.
+Five cases are **not** safe — a stale read gives a wrong answer with no error. They are in the model area, functions, or the metalake on/off flag:
-#### Summary: main risks, resolutions, and the staleness SLA
+| Change | Why a stale read is wrong, with no error |
+| --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| model version — update / add / remove URI | the URI points to the model files. An old URI silently loads the **wrong model files**. |
+| model version — update aliases | an alias silently points to the **wrong version**. |
+| model — latest version (after a new version is added on another node) | "get the latest version" silently returns an **old version**. |
+| function — add / update / remove implementation or definition | the implementation is the code the function runs. An old copy silently runs the **wrong function code**. |
+| metalake — disable | a node with a stale copy still thinks the metalake is on and **lets operations run** on a metalake that was turned off. (Turning it back on is safe: a stale node only throws "in use" by mistake.) |
Review Comment:
@yuqi1129 Could u sync this place final conclusion to me? What's the current state? What's the final state?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3595394504
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -225,16 +225,17 @@ Each row is `{metalake, entity_type, full_name, operate_type (ALTER | DROP), cre
### Writer side
-The cache now holds only metadata objects, and those **already write** an ALTER/DROP row to `entity_change_log` today. So the writer side needs **no change** — no new rows, no new columns, no new operate type:
+Most cached objects **already write** an ALTER/DROP row to `entity_change_log` today, so the writer side is almost unchanged — no new columns and no new operate type. The one addition is a change-log row for **tag and policy**, which are cached but do not emit one yet:
-| Change | Cached? | Writes a change-log row |
-| ----------------------------------------------------- | ------- | ----------------------- |
-| structural ALTER/DROP (table, schema, catalog, …) | yes | yes — already emitted |
-| user / group / role / tag / policy ALTER/DROP | no | not needed (not cached) |
-| model / model version / function ALTER/DROP | no | not needed (not cached) |
-| relation change (grant, set owner, attach tag/policy) | no | not needed (not cached) |
+| Change | Cached? | Writes a change-log row |
+| ----------------------------------------------------- | ------- | ------------------------------------- |
+| structural ALTER/DROP (table, schema, catalog, …) | yes | yes — already emitted |
+| tag / policy ALTER/DROP | yes | **add a new emit point** (none today) |
+| user / group / role ALTER/DROP | no | not needed (not cached) |
+| model / model version / function ALTER/DROP | no | not needed (not cached) |
+| relation change (grant, set owner, attach tag/policy) | no | not needed (not cached) |
-The existing structural rows are written in the same transaction as the entity write, so nothing new is added here.
+The existing structural rows are written in the same transaction as the entity write; the new tag/policy rows must be written the same way, in the same transaction as the tag/policy write.
Review Comment:
The key thing is to cache the relation between the tag and entity. The relation is used much more frequently when we do tag-based access control.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao merged PR #11738:
URL: https://github.com/apache/gravitino/pull/11738
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "roryqi (via GitHub)" <gi...@apache.org>.
roryqi commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3613993846
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -252,54 +254,68 @@ The entity store cache becomes a third consumer of the poller, next to the catal
### Consistency
-The cache is never the source of truth. The write path always reads the DB under the optimistic version lock, so eventual consistency can **never** cause a lost update or corrupt data. Its only observable effect is **bounded read staleness on non-writing nodes**: for up to one poll interval, a node other than the writer may serve an older value.
+The cache never holds the truth. Every write goes to the DB first, under the version lock, so a stale cache can **never** cause a lost update or a bad write. The only thing that can go wrong is that a read on **another node** returns an old value for a short time — at most one poll interval, until that node drops the key.
-- **Other nodes:** eventual — an entity key is dropped within one poll interval of the change.
-- **Writing node:** unchanged — it still clears its own cache on the write path, so it reads its own writes right away. Its own row is replayed later, which does nothing (clearing an already-clear key is a no-op).
-- **Write path:** unchanged — it reads the DB with the optimistic version check.
+So the real question is simple: when another node reads an old value, does it matter? We went through every alter and every drop, for every cached entity, one at a time. A stale read falls into one of two buckets:
-The rest of this section works through every way that staleness window can be observed, and how each is handled.
+- **The old value makes the next step fail with an error.** The user sees the error and tries again. This is safe.
+- **The old value is used silently and gives a wrong answer, with no error.** This is the dangerous kind.
-#### Staleness scenarios and mitigations
+We only need to worry about the second bucket.
-**1. Plain stale read (bounded, mostly tolerable).**
+#### Two groups of cached entities
-| # | Scenario | Effect | Possible mitigation |
-| - | -------------------------------------------------------------- |-----------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------|
-| 1 | Node A ALTERs a table (add column); B GETs it | B serves the old schema for up to one poll interval | Accept within the SLA window; a caller that needs an exact schema uses a consistent (cache-bypass) read |
-| 2 | Node A DROPs a table; B GETs it | B still reports it as present (cache hit) until the next poll | Accept — any write to it on B is re-validated against the DB and rejected as not-found, so no corruption |
-| 3 | RENAME (the old name behaves like a DROP); B GETs the old name | B keeps resolving the old name until the next poll; the new name misses → DB load | Same as DROP — bounded by the poll interval |
-| 4 | A property changes (e.g. Iceberg metadata-location); B GETs it | B returns the old location → a query on B may read an old snapshot/path | Highest-value case: offer a consistent (cache-bypass) read for location-sensitive callers, or use `redis` |
+The danger depends on where the real data comes from.
-**2. Read-your-writes across nodes.**
+**Group 1 — the data comes from the connector: table, view, topic, and schemas in external catalogs.** For these, Gravitino does not read the metadata from its own cache. On every load it asks the underlying system (Hive, Iceberg, JDBC, Kafka) for the current object, and uses the cached entity only for Gravitino's own id and audit fields. All nodes ask the same underlying system, so they all see the same thing. If the object was dropped or renamed, the connector call fails right away with a "not found" error. **This whole group is safe — nothing to do.**
-| # | Scenario | Effect | Possible mitigation |
-| - |---------------------------------------------------------------------|-------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
-| 5 | Through a load balancer, ALTER on A then an immediate read on B | Stale — violates session consistency; without sticky routing the change looks lost | Sticky sessions at the LB, or a client-supplied last-seen version that bypasses the cache when the copy is older; `redis` removes it entirely |
-| 6 | CREATE (rather than ALTER/DROP) | No problem — no negative caching and `list` skips the cache, so a new entity is visible at once | None needed |
+**Group 2 — the data comes from Gravitino's own store: metalake, catalog, managed schema, fileset, model, model version, function.** Here the cached entity *is* the answer, so a stale read really can return an old value. We looked at each alter in this group.
-**3. Cross-node read-modify-write.**
+(Views follow the same rule as tables: their definition is read through the connector on every load, so they sit in Group 1 and are safe.)
-| # | Scenario | Effect | Possible mitigation |
-| - | ------------------------------------------------------------------------------------- |-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------|
-| 7 | B reads stale value A and submits an update carrying A's version as the expected one | The optimistic lock rejects it on version mismatch — safe, but the user sees an unexpected conflict | Accept (correctness is preserved); reduce its frequency with the read-your-writes mitigations above |
+#### Walking through the alters in Group 2
-**4. Is the window actually bounded? — poller reliability (the real risk).** The "at most one poll interval" guarantee holds **only if the poller never drops a row**. If it does, the stale entry survives until the cache TTL, so this is the one place eventual consistency itself can break.
+Most alters are safe:
-| # | Scenario | Effect | Possible mitigation |
-| -- |-----------------------------------------------------------------------------------------------------------|-----------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------|
-| 8 | Commit-ordering gap / a skipped row | The key is never invalidated; stale until the TTL | Reuse the lag-safe, id-based polling already built for the change log (`#11736`); keep the cache TTL as a backstop |
-| 9 | Poller thread dies / DB briefly unreachable | That node serves stale data until the TTL | TTL backstop + monitor poller liveness/lag and alert |
-| 10 | Hierarchical DROP: only the container (schema) emits a row; children are cleared by a forward prefix scan | Correct as long as the prefix scan covers every child key | Cover with the hierarchical-drop test; confirm no child is written in a separate transaction that outlives the container row |
+| Change | What a stale read does | Safe? |
+| -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
+| rename (metalake, catalog, schema, fileset, model) | reading the old name returns a leftover copy, but any write to it goes to the DB and fails; the new name misses the cache and loads fresh from the DB | yes |
+| update comment | you see an old comment for a moment | yes |
+| set / remove property (metalake, model, fileset) | these properties do not change where the data lives | yes |
+| fileset storage location | **cannot be changed** — there is no alter for it, so it can never go stale | yes |
+| drop | for Group 1 the connector call fails; for a fileset the file path is gone and access fails | yes |
+| catalog changes | already handled today by a separate cross-node signal (`CatalogChangeLogListener`), not by this cache | yes |
-**5. Idempotency (no issue).** Replaying ALTER then DROP, in any order or duplicated, is safe: invalidation is idempotent, so out-of-order or repeated replay has no effect.
+Five cases are **not** safe — a stale read gives a wrong answer with no error. They are in the model area, functions, or the metalake on/off flag:
-#### Summary: main risks, resolutions, and the staleness SLA
+| Change | Why a stale read is wrong, with no error |
+| --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| model version — update / add / remove URI | the URI points to the model files. An old URI silently loads the **wrong model files**. |
+| model version — update aliases | an alias silently points to the **wrong version**. |
+| model — latest version (after a new version is added on another node) | "get the latest version" silently returns an **old version**. |
+| function — add / update / remove implementation or definition | the implementation is the code the function runs. An old copy silently runs the **wrong function code**. |
+| metalake — disable | a node with a stale copy still thinks the metalake is on and **lets operations run** on a metalake that was turned off. (Turning it back on is safe: a stale node only throws "in use" by mistake.) |
Review Comment:
From my view, eventual consistence is accepted. Performance is more important.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11737] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3536463224
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -0,0 +1,349 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+---
+title: "Multi-Node Support for the Entity Store Cache"
+status: "Draft"
+date: "2026-07-07"
+---
+
+## Background
+
+Gravitino has two caches:
+
+- The **jcasbin authorization cache** already works with more than one node.
+- The **entity store cache** does not. When a change happens on node A, only node A clears its cache. Node B keeps serving the old data until its entry expires.
+
+Because of this, the only safe way to run more than one node today is to turn the entity store cache off (`gravitino.cache.enabled=false`). That is bad for read-heavy catalogs, especially Iceberg.
+
+This document makes the entity store cache correct when running more than one node.
Review Comment:
This is a design-only PR, but the wording here reads like the change is already implemented ("makes the entity store cache correct"). To avoid misleading readers, please phrase this as a proposal/design rather than a completed behavior change.
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -0,0 +1,349 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+---
+title: "Multi-Node Support for the Entity Store Cache"
+status: "Draft"
+date: "2026-07-07"
+---
+
+## Background
+
+Gravitino has two caches:
+
+- The **jcasbin authorization cache** already works with more than one node.
+- The **entity store cache** does not. When a change happens on node A, only node A clears its cache. Node B keeps serving the old data until its entry expires.
+
+Because of this, the only safe way to run more than one node today is to turn the entity store cache off (`gravitino.cache.enabled=false`). That is bad for read-heavy catalogs, especially Iceberg.
+
+This document makes the entity store cache correct when running more than one node.
+
+## Goals and Non-Goals
+
+**Goals**
+
+- Make the entity store cache correct with more than one node, so `gravitino.cache.enabled=true` is safe.
+- Keep the cache **pluggable**: one SPI, chosen by `gravitino.cache.impl`. Ship `caffeine` as the default (no extra dependency) and `redis` as an option the user turns on by config.
+- Keep single-node behavior and the write path (the optimistic version lock) unchanged.
+
+**Non-Goals**
+
+- Replace the entity store or its write path. The cache sits in front of the store and is never the source of truth.
+- Add a cluster membership / gossip layer or any other complex distributed system. We only use the DB Gravitino already needs, or the external cache the user turns on.
+
+---
+
+## Current Cache Implementation
+
+`EntityCache` is already an SPI, chosen by `gravitino.cache.impl` and created by `CacheFactory`. There is one implementation today, `CaffeineEntityCache` (`caffeine`): an in-memory cache, **one copy per node**, with two kinds of entries:
+
+- **entity keys** `(ident, type)` → the entity itself;
+- **relation keys** `(ident, type, relType)` → the list of related entities, stored **in both directions** and kept in step by an in-process **reverse index** (`ReverseIndexCache`).
+
+On a write, the node clears the changed key and then uses the reverse index to clear the related keys. On a single node this is correct. The problem is that this clearing happens **only on the node that made the change** (`RelationalEntityStore` calls `cache.invalidate(...)` locally). Nothing tells the other nodes, so they serve old data until their entries expire.
+
+Some behavior is already safe with more than one node and does not change:
+
+| Already correct | Why |
+| ------------------------- | ---------------------------------------------------------------------------- |
+| Writes never lose updates | The write path reads the DB (not the cache) with an optimistic version check |
+| `list(namespace)` | Skips the cache, so it is never stale |
+| CREATE | Needs nothing: no negative caching, and `list` skips the cache |
+
+The rest of the problem splits in two:
+
+- **entity keys** are one-to-one. "table T changed" names exactly the key to drop, and any node can drop it. This is easy.
+- **relation keys** have a reverse key. Dropping one side (say a role) also means dropping the other side's key (each user that had the role), but "the role changed" does not say *which* users those are. The writing node knows them from its local reverse index; a remote node may not.
+
+That reverse key is the hard part. So the first question is whether the cache needs relations at all.
+
+---
+
+## Do We Need to Cache Relations?
+
+All the cross-node difficulty comes from relation caching (the reverse key and the write fan-out). Before building around it, we checked whether it is actually important for performance. It is not.
+
+**Who reads the relation cache.** The cached relation path is `RelationalEntityStore.listEntitiesByRelation`, which runs **one indexed SQL join** per call (`JDBCBackend.listEntitiesByRelation`). Its callers are all metadata governance managers:
+
+| Caller | Relation | API that uses it |
+| -------------------- | ---------------------------- |-----------------------------------|
+| `OwnerManager` | `OWNER_REL` | `GET .../owner` |
+| `RoleManager` | role relations | role / authorization management |
+| `FutureGrantManager` | role/user/group relations | applying future grants (admin op) |
+| `TagManager` | `TAG_METADATA_OBJECT_REL` | tag endpoints |
+| `PolicyManager` | `POLICY_METADATA_OBJECT_REL` | policy endpoints |
+
+**Who does not.** The two paths that must be fast do **not** use it:
+
+- **Core metadata reads** (`get` / `list` of table, schema, catalog, …) never call `listEntitiesByRelation`. Removing the relation cache does not affect them at all.
+- **Authorization checks** (`JcasbinAuthorizer`) read roles straight from mappers (`RoleMetaMapper.listRolesByUserId` / `listRolesByGroupId`), owner from its own `ownerRelCache` (which polls `owner_meta`), and id from its own `metadataIdCache`. It does not use the entity store relation cache at all. Relation caching was first added with authorization in mind, but authorization no longer uses it.
+
+**Cost of removing it.** Each call becomes one indexed query — not an N+1 (one query per item). No list endpoint loads relations per item in a loop. The one place a single request makes several queries is **tag / policy inheritance**: listing an object's tags also reads its parents (the object plus up to ~3 ancestors), so a tag lookup is up to ~4 single-row queries; the cache mainly saves re-reading popular parents. This is the only workload where removing the cache adds real DB load, and it can be measured today — those calls are already `@Monitored` (`baseMetricName = "listTagsForMetadataObject"`, `"getOwner"`, `"listPoliciesForMetadataObject"`).
+
+**Decision.** Remove relation caching from the entity store cache. Relation reads go straight to the DB (one indexed query each), the same as authorization already does. This is safe for the core read path and for authorization; the only risk is workloads with heavy tag/policy inheritance reads, which we can watch with the existing metrics and, if ever needed, address by adding precise relation caching back later.
+
+The result: the cache holds only **entity keys**, so cross-node invalidation becomes the easy one-to-one case, and (as both implementations show) each design loses its hardest part. The `ReverseIndexCache` and the two-direction relation keys are removed with it.
+
+But "cache only entity keys" is not the end of it: some entities **copy fields from other entities**, which would bring the reverse-lookup problem back. The next section works out which entities are actually safe to cache.
+
+---
+
+## Which Entities to Cache
+
+Dropping relations leaves the entity keys. But not every entity key is truly one-to-one. Some entities store fields **copied from other entities**, and those copies go stale when the other entity changes — which brings back the same reverse lookup we just removed. So we look at what each cached entity actually holds.
+
+**Self-contained vs. derived.**
+
+| Entity | Copies a field from another entity? | Safe to cache on its own? |
+| ------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------- |
+| metalake, catalog, schema, table, topic, model, view, fileset | no — holds only its own data (columns, properties, comment…) | yes |
+| tag, policy | no — associations are relations, not stored on the entity | yes |
+| user, group | yes — `roleNames` / `roleIds`, built from the user's roles | no |
+| role | yes — `securableObjects`, built from metadata objects | no |
+
+**Why user / group / role are a problem.**
+
+- `getUserByIdentifier` builds `roleNames` at read time by joining the user's roles (`UserMetaService` calls `RoleMetaService.listRolesByUserId`). If a role is dropped, it disappears from every user's list, but the user rows are not touched — so a cached user still lists the dropped role. Finding which users hold a role is a reverse lookup (role → users), exactly what dropping relations was meant to avoid.
+- `RoleEntity.securableObjects` has the same shape one level up: if a metadata object is renamed or dropped, a cached role that points at it is stale, and finding which roles point at an object is again a reverse lookup (object → roles).
+
+**Does authorization need these in the cache?** This is the key question, because authorization is the hot path. We checked `JcasbinAuthorizer`:
+
+- **user / group — no.** It reads user and group data through its own mappers (`UserMetaMapper`, `GroupMetaMapper`) into its own caches (`userRoleCache`, `groupRoleCache`), never through the entity store cache. So excluding user/group from the entity store cache does not affect authorization at all.
+- **role — only at cold start or after a change.** It does read role entities through the entity store (`entityStore.batchGet/get(ROLE)`), but only to (re)load a role's policies into the enforcer. Loaded roles are held in `loadedRoles`, a cache with `expireAfterAccess` (default 1 hour), so a role used at least once an hour never expires and the entity read is skipped. The entity read happens only on cold start, right after a role is edited, or after a role sits unused for over an hour — each a cheap one-time `batchGet`, not a per-request cost.
+
+So caching user, group, and role buys almost nothing (authorization does not depend on it) and costs a lot (the reverse-lookup problem comes back). tag and policy are safe to cache, but they are low-volume governance objects, not the read-heavy metadata the cache exists for.
+
+**Conclusion: cache only the basic metadata objects** — metalake, catalog, schema, table, topic, model, view, fileset. In code this is a small allowlist of entity types in the cache. Every cached entity is then self-contained and one-to-one, so cross-node invalidation stays precise with no reverse lookups. As a bonus, these entities already write ALTER/DROP rows to `entity_change_log`, so the writer side needs no change at all.
+
+The cache now holds only self-contained metadata objects. The next question is how to tell the other nodes to drop a key when it changes.
+
+---
+
+## Approaches to Multi-Node Consistency
+
+Keeping a per-node cache fresh across a cluster is a common problem: after a write on one node, no other node may serve stale data. The standard techniques:
+
+| Approach | How it works | Trade-off |
+| -------------------------- | ------------------------------------------------------------------------------------------- |------------------------------------------------------------------------------------|
+| TTL only | each entry expires after a fixed time | no work, but every node serves old data until the TTL passes |
+| Pub/sub broadcast | the writer sends "invalidate X"; every node subscribes | low delay, but needs a message bus and must handle missed messages |
+| Change-log table + poller | the writer records the change in a DB table in the same transaction; each node polls it | no new infrastructure (reuses the DB), survives restarts; up to one poll of delay |
+| Shared (distributed) cache | one copy for the whole cluster, so there is nothing per-node to keep fresh | no propagation at all, but needs Redis/Memcached and a network round-trip per read |
+
+### How other metadata systems solve it
+
+We looked at how similar systems keep **their own per-node cache** coherent across a cluster (not how they notify downstream/derived systems — that is a different problem). **The most common answer is a per-node cache kept fresh by polling or by an invalidation/broadcast signal; no one relies on plain TTL.** Each row below has a source:
+
+| System | How it keeps its per-node cache fresh across nodes | Technique |
+| ---------------------------------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------|
+| **Hive Metastore** (`CachedStore`) | each node's in-memory cache is updated by a background thread that **polls the `NOTIFICATION_LOG` table** (written by `DbNotificationListener`); the log is in commit order and is the source of truth, and reads fall back to the DB until the thread catches up [1][2] | change-log + poll |
+| **Apache Ranger** (plugins) | each plugin keeps a **local policy cache** and **periodically polls Ranger Admin** for a newer version (default every 30s, `policy.pollIntervalMs`), downloading only the delta when the version changes [3] | periodic poll |
+| **Confluent Schema Registry** | one compacted Kafka topic **`_schemas`** is the commit log and the source of truth; every node reads it in a background thread to build its **local materialized view** [4] | shared log |
+| **Apache Impala** (`catalogd`) | metadata changes are **broadcast to all coordinators through `statestored`**; in local-catalog mode coordinators instead **fetch on demand and cache locally**, and invalidate that cache on `catalogd` failover [5] | broadcast / on-demand pull |
+| **Redis** (client-side caching) | with `CLIENT TRACKING` the server remembers which keys each client cached and **pushes an invalidation message** (RESP3 push) when a key changes, so the client flushes its local copy [6] | server-push invalidation |
+| **CockroachDB** | each node caches table/schema descriptors under a **versioned lease**; at most the **two latest versions** can be leased at once, and a schema change waits for old leases to be released or to expire (lease duration on the order of minutes) before advancing [7] | versioned lease |
+| **Trino** (Hive connector) | a coordinator-side metastore cache with a fixed **TTL plus background refresh** (`hive.metastore-cache-ttl`, `hive.metastore-refresh-interval`); its own docs note this can return stale data [8] | TTL + refresh |
+
+Two things stand out: **polling a change/version log (Hive, Ranger) is the most common, no-new-infrastructure answer**, and the one system that relies on **TTL alone (Trino) is documented to sometimes return stale data** — even CockroachDB, which looks TTL-like, actually uses bounded leases with active release, not plain expiry. That is exactly why TTL is not enough for us.
+
+### The two approaches we pick
+
+The closest match to what Gravitino needs is **Hive Metastore's `CachedStore`**: a per-node cache kept fresh by polling a change log in the same DB. Gravitino already has both pieces — the DB as the source of truth, and an `entity_change_log` table with a poller (built for the jcasbin cache). So this works with **no new infrastructure**. This is the default, and we call it `caffeine`.
+
+The broadcast / pub-sub-invalidation systems (Impala's `statestored`, Redis client-side caching, Schema Registry's shared log) work well, but they need a **message bus that Gravitino does not have**, so pub/sub is left for later (see the [roadmap](#roadmap)). **TTL alone** (Trino) is rejected for the stale-read reason its own docs give. That leaves two approaches that need no new component:
+
+- **reuse the DB** — a per-node cache kept fresh by the change log. → `caffeine`
+- **use a shared copy** — for teams already running Redis and wanting strong consistency, keep one copy in Redis. → `redis`
+
+**Sources**
+
+1. Hive — *Synchronized Metastore Cache*: <https://cwiki.apache.org/confluence/display/Hive/Synchronized+Metastore+Cache> (and HIVE-18661: <https://issues.apache.org/jira/browse/HIVE-18661>)
+2. Hive — `CachedStore.java` / `DbNotificationListener.java`: <https://github.com/apache/hive/blob/master/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/cache/CachedStore.java>
+3. Confluent Schema Registry docs: <https://docs.confluent.io/platform/current/schema-registry/index.html>
+4. Apache Atlas — *Notifications*: <https://atlas.apache.org/2.0.0/Notifications.html>
+5. DataHub — *MetadataChangeProposal & MetadataChangeLog Events*: <https://docs.datahub.com/docs/advanced/mcp-mcl>
+6. Netflix TechBlog — *Metacat: Making Big Data Discoverable and Meaningful at Netflix*: <https://netflixtechblog.com/metacat-making-big-data-discoverable-and-meaningful-at-netflix-56fb36a53520>
+7. Trino — *Metastores* docs: <https://trino.io/docs/current/object-storage/metastores.html> (stale-read note: <https://github.com/trinodb/trino/issues/10512>)
+
+---
+
+## The Pluggable Framework
+
+We now have two approaches that behave differently — one keeps a local copy per node, the other keeps one shared copy. To let a user pick either one by config, the cache stays **pluggable**, and each implementation says which kind it is. The `EntityCache` SPI adds one method:
+
+```
+EntityCache.coherence() → LOCAL_PER_NODE | SHARED
+```
+
+- `LOCAL_PER_NODE` — each node has its own copy, so a write must be **sent to the other nodes** to clear their copies. `caffeine` is this kind.
+- `SHARED` — one copy for the whole cluster, so a write clears it once and every node sees it. Nothing to send. `redis` is this kind.
+
+The write path is the same for both; only what happens after the local clear differs, and that is decided by `coherence()`:
+
+<!-- diagram source: diagrams/coherence-gate.mmd (regenerate with mermaid-cli) -->
+
Review Comment:
This diagram link is currently broken: `design-docs/images/coherence-gate.png` does not exist in the repo (only `design-docs/images/roadmap.png` is present). Please either add the referenced image (and optionally its `.mmd` source) or adjust/remove the link so the doc renders without dead references.
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -0,0 +1,349 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+---
+title: "Multi-Node Support for the Entity Store Cache"
+status: "Draft"
+date: "2026-07-07"
+---
+
+## Background
+
+Gravitino has two caches:
+
+- The **jcasbin authorization cache** already works with more than one node.
+- The **entity store cache** does not. When a change happens on node A, only node A clears its cache. Node B keeps serving the old data until its entry expires.
+
+Because of this, the only safe way to run more than one node today is to turn the entity store cache off (`gravitino.cache.enabled=false`). That is bad for read-heavy catalogs, especially Iceberg.
+
+This document makes the entity store cache correct when running more than one node.
+
+## Goals and Non-Goals
+
+**Goals**
+
+- Make the entity store cache correct with more than one node, so `gravitino.cache.enabled=true` is safe.
+- Keep the cache **pluggable**: one SPI, chosen by `gravitino.cache.impl`. Ship `caffeine` as the default (no extra dependency) and `redis` as an option the user turns on by config.
+- Keep single-node behavior and the write path (the optimistic version lock) unchanged.
+
+**Non-Goals**
+
+- Replace the entity store or its write path. The cache sits in front of the store and is never the source of truth.
+- Add a cluster membership / gossip layer or any other complex distributed system. We only use the DB Gravitino already needs, or the external cache the user turns on.
+
+---
+
+## Current Cache Implementation
+
+`EntityCache` is already an SPI, chosen by `gravitino.cache.impl` and created by `CacheFactory`. There is one implementation today, `CaffeineEntityCache` (`caffeine`): an in-memory cache, **one copy per node**, with two kinds of entries:
+
+- **entity keys** `(ident, type)` → the entity itself;
+- **relation keys** `(ident, type, relType)` → the list of related entities, stored **in both directions** and kept in step by an in-process **reverse index** (`ReverseIndexCache`).
+
+On a write, the node clears the changed key and then uses the reverse index to clear the related keys. On a single node this is correct. The problem is that this clearing happens **only on the node that made the change** (`RelationalEntityStore` calls `cache.invalidate(...)` locally). Nothing tells the other nodes, so they serve old data until their entries expire.
+
+Some behavior is already safe with more than one node and does not change:
+
+| Already correct | Why |
+| ------------------------- | ---------------------------------------------------------------------------- |
+| Writes never lose updates | The write path reads the DB (not the cache) with an optimistic version check |
+| `list(namespace)` | Skips the cache, so it is never stale |
+| CREATE | Needs nothing: no negative caching, and `list` skips the cache |
+
+The rest of the problem splits in two:
+
+- **entity keys** are one-to-one. "table T changed" names exactly the key to drop, and any node can drop it. This is easy.
+- **relation keys** have a reverse key. Dropping one side (say a role) also means dropping the other side's key (each user that had the role), but "the role changed" does not say *which* users those are. The writing node knows them from its local reverse index; a remote node may not.
+
+That reverse key is the hard part. So the first question is whether the cache needs relations at all.
+
+---
+
+## Do We Need to Cache Relations?
+
+All the cross-node difficulty comes from relation caching (the reverse key and the write fan-out). Before building around it, we checked whether it is actually important for performance. It is not.
+
+**Who reads the relation cache.** The cached relation path is `RelationalEntityStore.listEntitiesByRelation`, which runs **one indexed SQL join** per call (`JDBCBackend.listEntitiesByRelation`). Its callers are all metadata governance managers:
+
+| Caller | Relation | API that uses it |
+| -------------------- | ---------------------------- |-----------------------------------|
+| `OwnerManager` | `OWNER_REL` | `GET .../owner` |
+| `RoleManager` | role relations | role / authorization management |
+| `FutureGrantManager` | role/user/group relations | applying future grants (admin op) |
+| `TagManager` | `TAG_METADATA_OBJECT_REL` | tag endpoints |
+| `PolicyManager` | `POLICY_METADATA_OBJECT_REL` | policy endpoints |
+
+**Who does not.** The two paths that must be fast do **not** use it:
+
+- **Core metadata reads** (`get` / `list` of table, schema, catalog, …) never call `listEntitiesByRelation`. Removing the relation cache does not affect them at all.
+- **Authorization checks** (`JcasbinAuthorizer`) read roles straight from mappers (`RoleMetaMapper.listRolesByUserId` / `listRolesByGroupId`), owner from its own `ownerRelCache` (which polls `owner_meta`), and id from its own `metadataIdCache`. It does not use the entity store relation cache at all. Relation caching was first added with authorization in mind, but authorization no longer uses it.
+
+**Cost of removing it.** Each call becomes one indexed query — not an N+1 (one query per item). No list endpoint loads relations per item in a loop. The one place a single request makes several queries is **tag / policy inheritance**: listing an object's tags also reads its parents (the object plus up to ~3 ancestors), so a tag lookup is up to ~4 single-row queries; the cache mainly saves re-reading popular parents. This is the only workload where removing the cache adds real DB load, and it can be measured today — those calls are already `@Monitored` (`baseMetricName = "listTagsForMetadataObject"`, `"getOwner"`, `"listPoliciesForMetadataObject"`).
+
+**Decision.** Remove relation caching from the entity store cache. Relation reads go straight to the DB (one indexed query each), the same as authorization already does. This is safe for the core read path and for authorization; the only risk is workloads with heavy tag/policy inheritance reads, which we can watch with the existing metrics and, if ever needed, address by adding precise relation caching back later.
+
+The result: the cache holds only **entity keys**, so cross-node invalidation becomes the easy one-to-one case, and (as both implementations show) each design loses its hardest part. The `ReverseIndexCache` and the two-direction relation keys are removed with it.
+
+But "cache only entity keys" is not the end of it: some entities **copy fields from other entities**, which would bring the reverse-lookup problem back. The next section works out which entities are actually safe to cache.
+
+---
+
+## Which Entities to Cache
+
+Dropping relations leaves the entity keys. But not every entity key is truly one-to-one. Some entities store fields **copied from other entities**, and those copies go stale when the other entity changes — which brings back the same reverse lookup we just removed. So we look at what each cached entity actually holds.
+
+**Self-contained vs. derived.**
+
+| Entity | Copies a field from another entity? | Safe to cache on its own? |
+| ------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------- |
+| metalake, catalog, schema, table, topic, model, view, fileset | no — holds only its own data (columns, properties, comment…) | yes |
+| tag, policy | no — associations are relations, not stored on the entity | yes |
+| user, group | yes — `roleNames` / `roleIds`, built from the user's roles | no |
+| role | yes — `securableObjects`, built from metadata objects | no |
+
+**Why user / group / role are a problem.**
+
+- `getUserByIdentifier` builds `roleNames` at read time by joining the user's roles (`UserMetaService` calls `RoleMetaService.listRolesByUserId`). If a role is dropped, it disappears from every user's list, but the user rows are not touched — so a cached user still lists the dropped role. Finding which users hold a role is a reverse lookup (role → users), exactly what dropping relations was meant to avoid.
+- `RoleEntity.securableObjects` has the same shape one level up: if a metadata object is renamed or dropped, a cached role that points at it is stale, and finding which roles point at an object is again a reverse lookup (object → roles).
+
+**Does authorization need these in the cache?** This is the key question, because authorization is the hot path. We checked `JcasbinAuthorizer`:
+
+- **user / group — no.** It reads user and group data through its own mappers (`UserMetaMapper`, `GroupMetaMapper`) into its own caches (`userRoleCache`, `groupRoleCache`), never through the entity store cache. So excluding user/group from the entity store cache does not affect authorization at all.
+- **role — only at cold start or after a change.** It does read role entities through the entity store (`entityStore.batchGet/get(ROLE)`), but only to (re)load a role's policies into the enforcer. Loaded roles are held in `loadedRoles`, a cache with `expireAfterAccess` (default 1 hour), so a role used at least once an hour never expires and the entity read is skipped. The entity read happens only on cold start, right after a role is edited, or after a role sits unused for over an hour — each a cheap one-time `batchGet`, not a per-request cost.
+
+So caching user, group, and role buys almost nothing (authorization does not depend on it) and costs a lot (the reverse-lookup problem comes back). tag and policy are safe to cache, but they are low-volume governance objects, not the read-heavy metadata the cache exists for.
+
+**Conclusion: cache only the basic metadata objects** — metalake, catalog, schema, table, topic, model, view, fileset. In code this is a small allowlist of entity types in the cache. Every cached entity is then self-contained and one-to-one, so cross-node invalidation stays precise with no reverse lookups. As a bonus, these entities already write ALTER/DROP rows to `entity_change_log`, so the writer side needs no change at all.
+
+The cache now holds only self-contained metadata objects. The next question is how to tell the other nodes to drop a key when it changes.
+
+---
+
+## Approaches to Multi-Node Consistency
+
+Keeping a per-node cache fresh across a cluster is a common problem: after a write on one node, no other node may serve stale data. The standard techniques:
+
+| Approach | How it works | Trade-off |
+| -------------------------- | ------------------------------------------------------------------------------------------- |------------------------------------------------------------------------------------|
+| TTL only | each entry expires after a fixed time | no work, but every node serves old data until the TTL passes |
+| Pub/sub broadcast | the writer sends "invalidate X"; every node subscribes | low delay, but needs a message bus and must handle missed messages |
+| Change-log table + poller | the writer records the change in a DB table in the same transaction; each node polls it | no new infrastructure (reuses the DB), survives restarts; up to one poll of delay |
+| Shared (distributed) cache | one copy for the whole cluster, so there is nothing per-node to keep fresh | no propagation at all, but needs Redis/Memcached and a network round-trip per read |
+
+### How other metadata systems solve it
+
+We looked at how similar systems keep **their own per-node cache** coherent across a cluster (not how they notify downstream/derived systems — that is a different problem). **The most common answer is a per-node cache kept fresh by polling or by an invalidation/broadcast signal; no one relies on plain TTL.** Each row below has a source:
+
+| System | How it keeps its per-node cache fresh across nodes | Technique |
+| ---------------------------------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------|
+| **Hive Metastore** (`CachedStore`) | each node's in-memory cache is updated by a background thread that **polls the `NOTIFICATION_LOG` table** (written by `DbNotificationListener`); the log is in commit order and is the source of truth, and reads fall back to the DB until the thread catches up [1][2] | change-log + poll |
+| **Apache Ranger** (plugins) | each plugin keeps a **local policy cache** and **periodically polls Ranger Admin** for a newer version (default every 30s, `policy.pollIntervalMs`), downloading only the delta when the version changes [3] | periodic poll |
+| **Confluent Schema Registry** | one compacted Kafka topic **`_schemas`** is the commit log and the source of truth; every node reads it in a background thread to build its **local materialized view** [4] | shared log |
+| **Apache Impala** (`catalogd`) | metadata changes are **broadcast to all coordinators through `statestored`**; in local-catalog mode coordinators instead **fetch on demand and cache locally**, and invalidate that cache on `catalogd` failover [5] | broadcast / on-demand pull |
+| **Redis** (client-side caching) | with `CLIENT TRACKING` the server remembers which keys each client cached and **pushes an invalidation message** (RESP3 push) when a key changes, so the client flushes its local copy [6] | server-push invalidation |
+| **CockroachDB** | each node caches table/schema descriptors under a **versioned lease**; at most the **two latest versions** can be leased at once, and a schema change waits for old leases to be released or to expire (lease duration on the order of minutes) before advancing [7] | versioned lease |
+| **Trino** (Hive connector) | a coordinator-side metastore cache with a fixed **TTL plus background refresh** (`hive.metastore-cache-ttl`, `hive.metastore-refresh-interval`); its own docs note this can return stale data [8] | TTL + refresh |
+
+Two things stand out: **polling a change/version log (Hive, Ranger) is the most common, no-new-infrastructure answer**, and the one system that relies on **TTL alone (Trino) is documented to sometimes return stale data** — even CockroachDB, which looks TTL-like, actually uses bounded leases with active release, not plain expiry. That is exactly why TTL is not enough for us.
+
+### The two approaches we pick
+
+The closest match to what Gravitino needs is **Hive Metastore's `CachedStore`**: a per-node cache kept fresh by polling a change log in the same DB. Gravitino already has both pieces — the DB as the source of truth, and an `entity_change_log` table with a poller (built for the jcasbin cache). So this works with **no new infrastructure**. This is the default, and we call it `caffeine`.
+
+The broadcast / pub-sub-invalidation systems (Impala's `statestored`, Redis client-side caching, Schema Registry's shared log) work well, but they need a **message bus that Gravitino does not have**, so pub/sub is left for later (see the [roadmap](#roadmap)). **TTL alone** (Trino) is rejected for the stale-read reason its own docs give. That leaves two approaches that need no new component:
+
+- **reuse the DB** — a per-node cache kept fresh by the change log. → `caffeine`
+- **use a shared copy** — for teams already running Redis and wanting strong consistency, keep one copy in Redis. → `redis`
+
+**Sources**
+
+1. Hive — *Synchronized Metastore Cache*: <https://cwiki.apache.org/confluence/display/Hive/Synchronized+Metastore+Cache> (and HIVE-18661: <https://issues.apache.org/jira/browse/HIVE-18661>)
+2. Hive — `CachedStore.java` / `DbNotificationListener.java`: <https://github.com/apache/hive/blob/master/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/cache/CachedStore.java>
+3. Confluent Schema Registry docs: <https://docs.confluent.io/platform/current/schema-registry/index.html>
+4. Apache Atlas — *Notifications*: <https://atlas.apache.org/2.0.0/Notifications.html>
+5. DataHub — *MetadataChangeProposal & MetadataChangeLog Events*: <https://docs.datahub.com/docs/advanced/mcp-mcl>
+6. Netflix TechBlog — *Metacat: Making Big Data Discoverable and Meaningful at Netflix*: <https://netflixtechblog.com/metacat-making-big-data-discoverable-and-meaningful-at-netflix-56fb36a53520>
+7. Trino — *Metastores* docs: <https://trino.io/docs/current/object-storage/metastores.html> (stale-read note: <https://github.com/trinodb/trino/issues/10512>)
+
+---
+
+## The Pluggable Framework
+
+We now have two approaches that behave differently — one keeps a local copy per node, the other keeps one shared copy. To let a user pick either one by config, the cache stays **pluggable**, and each implementation says which kind it is. The `EntityCache` SPI adds one method:
+
+```
+EntityCache.coherence() → LOCAL_PER_NODE | SHARED
+```
+
+- `LOCAL_PER_NODE` — each node has its own copy, so a write must be **sent to the other nodes** to clear their copies. `caffeine` is this kind.
+- `SHARED` — one copy for the whole cluster, so a write clears it once and every node sees it. Nothing to send. `redis` is this kind.
+
+The write path is the same for both; only what happens after the local clear differs, and that is decided by `coherence()`:
+
+<!-- diagram source: diagrams/coherence-gate.mmd (regenerate with mermaid-cli) -->
+
+
+`CacheFactory.ENTITY_CACHES` is already a name → class table loaded by reflection, so adding `redis` next to `caffeine` is one new table entry with no change to the callers.
+
+The rest of this document describes each implementation — first the default local cache, then the shared cache.
+
+---
+
+# Implementation A — Caffeine (`caffeine`, `LOCAL_PER_NODE`, default)
+
+With only self-contained metadata objects cached, "entity X changed" names exactly the key to drop, and **any node can drop it** — no reverse key, no fan-out. The channel to carry "entity X changed" to the other nodes already exists and is already used by other caches.
+
+<!-- diagram source: diagrams/entity-key-invalidation.mmd (regenerate with mermaid-cli) -->
+
Review Comment:
This diagram link is currently broken: `design-docs/images/entity-key-invalidation.png` (and the referenced `diagrams/entity-key-invalidation.mmd`) are not present in the repo. Please add the missing asset(s) or remove/update these references so the doc doesn’t contain dead links.
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -0,0 +1,349 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+---
+title: "Multi-Node Support for the Entity Store Cache"
+status: "Draft"
+date: "2026-07-07"
+---
Review Comment:
PR description/issue text says the design doc is named `design-docs/entity-cache-multinode-changelog-design.md`, but the file added in this PR is `design-docs/gravitino-entity-cache-multinode-design.md`. Please align the filename/path with the PR description (or update the PR description) to avoid confusion when people search for the referenced doc.
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -0,0 +1,349 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+---
+title: "Multi-Node Support for the Entity Store Cache"
+status: "Draft"
+date: "2026-07-07"
+---
+
+## Background
+
+Gravitino has two caches:
+
+- The **jcasbin authorization cache** already works with more than one node.
+- The **entity store cache** does not. When a change happens on node A, only node A clears its cache. Node B keeps serving the old data until its entry expires.
+
+Because of this, the only safe way to run more than one node today is to turn the entity store cache off (`gravitino.cache.enabled=false`). That is bad for read-heavy catalogs, especially Iceberg.
+
+This document makes the entity store cache correct when running more than one node.
+
+## Goals and Non-Goals
+
+**Goals**
+
+- Make the entity store cache correct with more than one node, so `gravitino.cache.enabled=true` is safe.
+- Keep the cache **pluggable**: one SPI, chosen by `gravitino.cache.impl`. Ship `caffeine` as the default (no extra dependency) and `redis` as an option the user turns on by config.
+- Keep single-node behavior and the write path (the optimistic version lock) unchanged.
+
+**Non-Goals**
+
+- Replace the entity store or its write path. The cache sits in front of the store and is never the source of truth.
+- Add a cluster membership / gossip layer or any other complex distributed system. We only use the DB Gravitino already needs, or the external cache the user turns on.
+
+---
+
+## Current Cache Implementation
+
+`EntityCache` is already an SPI, chosen by `gravitino.cache.impl` and created by `CacheFactory`. There is one implementation today, `CaffeineEntityCache` (`caffeine`): an in-memory cache, **one copy per node**, with two kinds of entries:
+
+- **entity keys** `(ident, type)` → the entity itself;
+- **relation keys** `(ident, type, relType)` → the list of related entities, stored **in both directions** and kept in step by an in-process **reverse index** (`ReverseIndexCache`).
+
+On a write, the node clears the changed key and then uses the reverse index to clear the related keys. On a single node this is correct. The problem is that this clearing happens **only on the node that made the change** (`RelationalEntityStore` calls `cache.invalidate(...)` locally). Nothing tells the other nodes, so they serve old data until their entries expire.
+
+Some behavior is already safe with more than one node and does not change:
+
+| Already correct | Why |
+| ------------------------- | ---------------------------------------------------------------------------- |
+| Writes never lose updates | The write path reads the DB (not the cache) with an optimistic version check |
+| `list(namespace)` | Skips the cache, so it is never stale |
+| CREATE | Needs nothing: no negative caching, and `list` skips the cache |
+
+The rest of the problem splits in two:
+
+- **entity keys** are one-to-one. "table T changed" names exactly the key to drop, and any node can drop it. This is easy.
+- **relation keys** have a reverse key. Dropping one side (say a role) also means dropping the other side's key (each user that had the role), but "the role changed" does not say *which* users those are. The writing node knows them from its local reverse index; a remote node may not.
+
+That reverse key is the hard part. So the first question is whether the cache needs relations at all.
+
+---
+
+## Do We Need to Cache Relations?
+
+All the cross-node difficulty comes from relation caching (the reverse key and the write fan-out). Before building around it, we checked whether it is actually important for performance. It is not.
+
+**Who reads the relation cache.** The cached relation path is `RelationalEntityStore.listEntitiesByRelation`, which runs **one indexed SQL join** per call (`JDBCBackend.listEntitiesByRelation`). Its callers are all metadata governance managers:
+
+| Caller | Relation | API that uses it |
+| -------------------- | ---------------------------- |-----------------------------------|
+| `OwnerManager` | `OWNER_REL` | `GET .../owner` |
+| `RoleManager` | role relations | role / authorization management |
+| `FutureGrantManager` | role/user/group relations | applying future grants (admin op) |
+| `TagManager` | `TAG_METADATA_OBJECT_REL` | tag endpoints |
+| `PolicyManager` | `POLICY_METADATA_OBJECT_REL` | policy endpoints |
+
+**Who does not.** The two paths that must be fast do **not** use it:
+
+- **Core metadata reads** (`get` / `list` of table, schema, catalog, …) never call `listEntitiesByRelation`. Removing the relation cache does not affect them at all.
+- **Authorization checks** (`JcasbinAuthorizer`) read roles straight from mappers (`RoleMetaMapper.listRolesByUserId` / `listRolesByGroupId`), owner from its own `ownerRelCache` (which polls `owner_meta`), and id from its own `metadataIdCache`. It does not use the entity store relation cache at all. Relation caching was first added with authorization in mind, but authorization no longer uses it.
+
+**Cost of removing it.** Each call becomes one indexed query — not an N+1 (one query per item). No list endpoint loads relations per item in a loop. The one place a single request makes several queries is **tag / policy inheritance**: listing an object's tags also reads its parents (the object plus up to ~3 ancestors), so a tag lookup is up to ~4 single-row queries; the cache mainly saves re-reading popular parents. This is the only workload where removing the cache adds real DB load, and it can be measured today — those calls are already `@Monitored` (`baseMetricName = "listTagsForMetadataObject"`, `"getOwner"`, `"listPoliciesForMetadataObject"`).
+
+**Decision.** Remove relation caching from the entity store cache. Relation reads go straight to the DB (one indexed query each), the same as authorization already does. This is safe for the core read path and for authorization; the only risk is workloads with heavy tag/policy inheritance reads, which we can watch with the existing metrics and, if ever needed, address by adding precise relation caching back later.
+
+The result: the cache holds only **entity keys**, so cross-node invalidation becomes the easy one-to-one case, and (as both implementations show) each design loses its hardest part. The `ReverseIndexCache` and the two-direction relation keys are removed with it.
+
+But "cache only entity keys" is not the end of it: some entities **copy fields from other entities**, which would bring the reverse-lookup problem back. The next section works out which entities are actually safe to cache.
+
+---
+
+## Which Entities to Cache
+
+Dropping relations leaves the entity keys. But not every entity key is truly one-to-one. Some entities store fields **copied from other entities**, and those copies go stale when the other entity changes — which brings back the same reverse lookup we just removed. So we look at what each cached entity actually holds.
+
+**Self-contained vs. derived.**
+
+| Entity | Copies a field from another entity? | Safe to cache on its own? |
+| ------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------- |
+| metalake, catalog, schema, table, topic, model, view, fileset | no — holds only its own data (columns, properties, comment…) | yes |
+| tag, policy | no — associations are relations, not stored on the entity | yes |
+| user, group | yes — `roleNames` / `roleIds`, built from the user's roles | no |
+| role | yes — `securableObjects`, built from metadata objects | no |
+
+**Why user / group / role are a problem.**
+
+- `getUserByIdentifier` builds `roleNames` at read time by joining the user's roles (`UserMetaService` calls `RoleMetaService.listRolesByUserId`). If a role is dropped, it disappears from every user's list, but the user rows are not touched — so a cached user still lists the dropped role. Finding which users hold a role is a reverse lookup (role → users), exactly what dropping relations was meant to avoid.
+- `RoleEntity.securableObjects` has the same shape one level up: if a metadata object is renamed or dropped, a cached role that points at it is stale, and finding which roles point at an object is again a reverse lookup (object → roles).
+
+**Does authorization need these in the cache?** This is the key question, because authorization is the hot path. We checked `JcasbinAuthorizer`:
+
+- **user / group — no.** It reads user and group data through its own mappers (`UserMetaMapper`, `GroupMetaMapper`) into its own caches (`userRoleCache`, `groupRoleCache`), never through the entity store cache. So excluding user/group from the entity store cache does not affect authorization at all.
+- **role — only at cold start or after a change.** It does read role entities through the entity store (`entityStore.batchGet/get(ROLE)`), but only to (re)load a role's policies into the enforcer. Loaded roles are held in `loadedRoles`, a cache with `expireAfterAccess` (default 1 hour), so a role used at least once an hour never expires and the entity read is skipped. The entity read happens only on cold start, right after a role is edited, or after a role sits unused for over an hour — each a cheap one-time `batchGet`, not a per-request cost.
+
+So caching user, group, and role buys almost nothing (authorization does not depend on it) and costs a lot (the reverse-lookup problem comes back). tag and policy are safe to cache, but they are low-volume governance objects, not the read-heavy metadata the cache exists for.
+
+**Conclusion: cache only the basic metadata objects** — metalake, catalog, schema, table, topic, model, view, fileset. In code this is a small allowlist of entity types in the cache. Every cached entity is then self-contained and one-to-one, so cross-node invalidation stays precise with no reverse lookups. As a bonus, these entities already write ALTER/DROP rows to `entity_change_log`, so the writer side needs no change at all.
+
+The cache now holds only self-contained metadata objects. The next question is how to tell the other nodes to drop a key when it changes.
+
+---
+
+## Approaches to Multi-Node Consistency
+
+Keeping a per-node cache fresh across a cluster is a common problem: after a write on one node, no other node may serve stale data. The standard techniques:
+
+| Approach | How it works | Trade-off |
+| -------------------------- | ------------------------------------------------------------------------------------------- |------------------------------------------------------------------------------------|
+| TTL only | each entry expires after a fixed time | no work, but every node serves old data until the TTL passes |
+| Pub/sub broadcast | the writer sends "invalidate X"; every node subscribes | low delay, but needs a message bus and must handle missed messages |
+| Change-log table + poller | the writer records the change in a DB table in the same transaction; each node polls it | no new infrastructure (reuses the DB), survives restarts; up to one poll of delay |
+| Shared (distributed) cache | one copy for the whole cluster, so there is nothing per-node to keep fresh | no propagation at all, but needs Redis/Memcached and a network round-trip per read |
+
+### How other metadata systems solve it
+
+We looked at how similar systems keep **their own per-node cache** coherent across a cluster (not how they notify downstream/derived systems — that is a different problem). **The most common answer is a per-node cache kept fresh by polling or by an invalidation/broadcast signal; no one relies on plain TTL.** Each row below has a source:
+
+| System | How it keeps its per-node cache fresh across nodes | Technique |
+| ---------------------------------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------|
+| **Hive Metastore** (`CachedStore`) | each node's in-memory cache is updated by a background thread that **polls the `NOTIFICATION_LOG` table** (written by `DbNotificationListener`); the log is in commit order and is the source of truth, and reads fall back to the DB until the thread catches up [1][2] | change-log + poll |
+| **Apache Ranger** (plugins) | each plugin keeps a **local policy cache** and **periodically polls Ranger Admin** for a newer version (default every 30s, `policy.pollIntervalMs`), downloading only the delta when the version changes [3] | periodic poll |
+| **Confluent Schema Registry** | one compacted Kafka topic **`_schemas`** is the commit log and the source of truth; every node reads it in a background thread to build its **local materialized view** [4] | shared log |
+| **Apache Impala** (`catalogd`) | metadata changes are **broadcast to all coordinators through `statestored`**; in local-catalog mode coordinators instead **fetch on demand and cache locally**, and invalidate that cache on `catalogd` failover [5] | broadcast / on-demand pull |
+| **Redis** (client-side caching) | with `CLIENT TRACKING` the server remembers which keys each client cached and **pushes an invalidation message** (RESP3 push) when a key changes, so the client flushes its local copy [6] | server-push invalidation |
+| **CockroachDB** | each node caches table/schema descriptors under a **versioned lease**; at most the **two latest versions** can be leased at once, and a schema change waits for old leases to be released or to expire (lease duration on the order of minutes) before advancing [7] | versioned lease |
+| **Trino** (Hive connector) | a coordinator-side metastore cache with a fixed **TTL plus background refresh** (`hive.metastore-cache-ttl`, `hive.metastore-refresh-interval`); its own docs note this can return stale data [8] | TTL + refresh |
+
+Two things stand out: **polling a change/version log (Hive, Ranger) is the most common, no-new-infrastructure answer**, and the one system that relies on **TTL alone (Trino) is documented to sometimes return stale data** — even CockroachDB, which looks TTL-like, actually uses bounded leases with active release, not plain expiry. That is exactly why TTL is not enough for us.
+
+### The two approaches we pick
+
+The closest match to what Gravitino needs is **Hive Metastore's `CachedStore`**: a per-node cache kept fresh by polling a change log in the same DB. Gravitino already has both pieces — the DB as the source of truth, and an `entity_change_log` table with a poller (built for the jcasbin cache). So this works with **no new infrastructure**. This is the default, and we call it `caffeine`.
+
+The broadcast / pub-sub-invalidation systems (Impala's `statestored`, Redis client-side caching, Schema Registry's shared log) work well, but they need a **message bus that Gravitino does not have**, so pub/sub is left for later (see the [roadmap](#roadmap)). **TTL alone** (Trino) is rejected for the stale-read reason its own docs give. That leaves two approaches that need no new component:
+
+- **reuse the DB** — a per-node cache kept fresh by the change log. → `caffeine`
+- **use a shared copy** — for teams already running Redis and wanting strong consistency, keep one copy in Redis. → `redis`
+
+**Sources**
+
+1. Hive — *Synchronized Metastore Cache*: <https://cwiki.apache.org/confluence/display/Hive/Synchronized+Metastore+Cache> (and HIVE-18661: <https://issues.apache.org/jira/browse/HIVE-18661>)
+2. Hive — `CachedStore.java` / `DbNotificationListener.java`: <https://github.com/apache/hive/blob/master/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/cache/CachedStore.java>
+3. Confluent Schema Registry docs: <https://docs.confluent.io/platform/current/schema-registry/index.html>
+4. Apache Atlas — *Notifications*: <https://atlas.apache.org/2.0.0/Notifications.html>
+5. DataHub — *MetadataChangeProposal & MetadataChangeLog Events*: <https://docs.datahub.com/docs/advanced/mcp-mcl>
+6. Netflix TechBlog — *Metacat: Making Big Data Discoverable and Meaningful at Netflix*: <https://netflixtechblog.com/metacat-making-big-data-discoverable-and-meaningful-at-netflix-56fb36a53520>
+7. Trino — *Metastores* docs: <https://trino.io/docs/current/object-storage/metastores.html> (stale-read note: <https://github.com/trinodb/trino/issues/10512>)
+
+---
+
+## The Pluggable Framework
+
+We now have two approaches that behave differently — one keeps a local copy per node, the other keeps one shared copy. To let a user pick either one by config, the cache stays **pluggable**, and each implementation says which kind it is. The `EntityCache` SPI adds one method:
+
+```
+EntityCache.coherence() → LOCAL_PER_NODE | SHARED
+```
+
+- `LOCAL_PER_NODE` — each node has its own copy, so a write must be **sent to the other nodes** to clear their copies. `caffeine` is this kind.
+- `SHARED` — one copy for the whole cluster, so a write clears it once and every node sees it. Nothing to send. `redis` is this kind.
+
+The write path is the same for both; only what happens after the local clear differs, and that is decided by `coherence()`:
+
+<!-- diagram source: diagrams/coherence-gate.mmd (regenerate with mermaid-cli) -->
+
+
+`CacheFactory.ENTITY_CACHES` is already a name → class table loaded by reflection, so adding `redis` next to `caffeine` is one new table entry with no change to the callers.
+
+The rest of this document describes each implementation — first the default local cache, then the shared cache.
+
+---
+
+# Implementation A — Caffeine (`caffeine`, `LOCAL_PER_NODE`, default)
+
+With only self-contained metadata objects cached, "entity X changed" names exactly the key to drop, and **any node can drop it** — no reverse key, no fan-out. The channel to carry "entity X changed" to the other nodes already exists and is already used by other caches.
+
+<!-- diagram source: diagrams/entity-key-invalidation.mmd (regenerate with mermaid-cli) -->
+
+
+### Reuse the existing transport
+
+`entity_change_log` and `EntityChangeLogPoller` already exist and are already used by two consumers:
+
+- `CatalogChangeLogListener` → clears `CatalogManager`'s catalog cache;
+- `JcasbinChangeListener` → clears jcasbin's **id-mapping cache** (`metadataIdCache`).
+
+Each row is `{metalake, entity_type, full_name, operate_type (ALTER | DROP), created_at}`. The structural MetaServices (metalake, catalog, schema, table, topic, model, view, fileset) already write a row on ALTER/DROP. We add the entity store cache as a **third consumer** of the same poller.
+
+### Writer side
+
+The cache now holds only metadata objects, and those **already write** an ALTER/DROP row to `entity_change_log` today. So the writer side needs **no change** — no new rows, no new columns, no new operate type:
+
+| Change | Cached? | Writes a change-log row |
+| ----------------------------------------------------- | ------- | ----------------------- |
+| structural ALTER/DROP (table, schema, catalog, …) | yes | yes — already emitted |
+| user / group / role / tag / policy ALTER/DROP | no | not needed (not cached) |
+| relation change (grant, set owner, attach tag/policy) | no | not needed (not cached) |
+
+The existing structural rows are written in the same transaction as the entity write, so nothing new is added here.
+
+### Reader side
+
+A new `EntityChangeLogListener` for the entity store cache runs on the **same poller** and replays each row as a direct invalidation:
+
+```
+onEntityChange(rows):
+ for row in rows:
+ cache.invalidate(identOf(row), row.entity_type) # drop exactly this entity key
+```
+
+Dropping a container (for example a schema) must also drop its cached children. That uses the **forward** prefix scan the cache already has (`cacheIndex`), on the local node — the reverse index is not involved. This is the only remaining cascade.
+
+### A third consumer of the existing feed
+
+The entity store cache becomes a third consumer of the poller, next to the catalog cache and the jcasbin id-mapping cache. All three read the same structural ALTER/DROP rows that already exist — the entity store cache clears its entity key, the catalog cache clears its catalog, jcasbin clears its id mapping. There is no new row type, so the existing consumers do not change.
+
+### Consistency
+
+- **Other nodes:** eventual — an entity key is dropped within one poll interval of the change.
+- **Writing node:** unchanged — it still clears its own cache on the write path, so it reads its own writes right away. Its own row is replayed later, which does nothing (clearing an already-clear key is a no-op).
+- **Write path:** unchanged — it reads the DB with the optimistic version check.
+
+---
+
+# Implementation B — Redis (`redis`, `SHARED`, optional)
+
+The local cache keeps one copy per node and must send every change to the other nodes. The shared cache does the opposite: **one copy for the whole cluster**, so a write clears it once and every node sees it — no change log, no poller.
+
+<!-- diagram source: diagrams/shared-cache.mmd (regenerate with mermaid-cli) -->
+
Review Comment:
This diagram link is currently broken: `design-docs/images/shared-cache.png` (and the referenced `diagrams/shared-cache.mmd`) are not present in the repo. Please add the missing asset(s) or remove/update these references so the doc doesn’t contain dead links.
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -0,0 +1,349 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+---
+title: "Multi-Node Support for the Entity Store Cache"
+status: "Draft"
+date: "2026-07-07"
+---
+
+## Background
+
+Gravitino has two caches:
+
+- The **jcasbin authorization cache** already works with more than one node.
+- The **entity store cache** does not. When a change happens on node A, only node A clears its cache. Node B keeps serving the old data until its entry expires.
+
+Because of this, the only safe way to run more than one node today is to turn the entity store cache off (`gravitino.cache.enabled=false`). That is bad for read-heavy catalogs, especially Iceberg.
+
+This document makes the entity store cache correct when running more than one node.
+
+## Goals and Non-Goals
+
+**Goals**
+
+- Make the entity store cache correct with more than one node, so `gravitino.cache.enabled=true` is safe.
+- Keep the cache **pluggable**: one SPI, chosen by `gravitino.cache.impl`. Ship `caffeine` as the default (no extra dependency) and `redis` as an option the user turns on by config.
+- Keep single-node behavior and the write path (the optimistic version lock) unchanged.
+
+**Non-Goals**
+
+- Replace the entity store or its write path. The cache sits in front of the store and is never the source of truth.
+- Add a cluster membership / gossip layer or any other complex distributed system. We only use the DB Gravitino already needs, or the external cache the user turns on.
+
+---
+
+## Current Cache Implementation
+
+`EntityCache` is already an SPI, chosen by `gravitino.cache.impl` and created by `CacheFactory`. There is one implementation today, `CaffeineEntityCache` (`caffeine`): an in-memory cache, **one copy per node**, with two kinds of entries:
+
+- **entity keys** `(ident, type)` → the entity itself;
+- **relation keys** `(ident, type, relType)` → the list of related entities, stored **in both directions** and kept in step by an in-process **reverse index** (`ReverseIndexCache`).
+
+On a write, the node clears the changed key and then uses the reverse index to clear the related keys. On a single node this is correct. The problem is that this clearing happens **only on the node that made the change** (`RelationalEntityStore` calls `cache.invalidate(...)` locally). Nothing tells the other nodes, so they serve old data until their entries expire.
+
+Some behavior is already safe with more than one node and does not change:
+
+| Already correct | Why |
+| ------------------------- | ---------------------------------------------------------------------------- |
+| Writes never lose updates | The write path reads the DB (not the cache) with an optimistic version check |
+| `list(namespace)` | Skips the cache, so it is never stale |
+| CREATE | Needs nothing: no negative caching, and `list` skips the cache |
+
+The rest of the problem splits in two:
+
+- **entity keys** are one-to-one. "table T changed" names exactly the key to drop, and any node can drop it. This is easy.
+- **relation keys** have a reverse key. Dropping one side (say a role) also means dropping the other side's key (each user that had the role), but "the role changed" does not say *which* users those are. The writing node knows them from its local reverse index; a remote node may not.
+
+That reverse key is the hard part. So the first question is whether the cache needs relations at all.
+
+---
+
+## Do We Need to Cache Relations?
+
+All the cross-node difficulty comes from relation caching (the reverse key and the write fan-out). Before building around it, we checked whether it is actually important for performance. It is not.
+
+**Who reads the relation cache.** The cached relation path is `RelationalEntityStore.listEntitiesByRelation`, which runs **one indexed SQL join** per call (`JDBCBackend.listEntitiesByRelation`). Its callers are all metadata governance managers:
+
+| Caller | Relation | API that uses it |
+| -------------------- | ---------------------------- |-----------------------------------|
+| `OwnerManager` | `OWNER_REL` | `GET .../owner` |
+| `RoleManager` | role relations | role / authorization management |
+| `FutureGrantManager` | role/user/group relations | applying future grants (admin op) |
+| `TagManager` | `TAG_METADATA_OBJECT_REL` | tag endpoints |
+| `PolicyManager` | `POLICY_METADATA_OBJECT_REL` | policy endpoints |
+
+**Who does not.** The two paths that must be fast do **not** use it:
+
+- **Core metadata reads** (`get` / `list` of table, schema, catalog, …) never call `listEntitiesByRelation`. Removing the relation cache does not affect them at all.
+- **Authorization checks** (`JcasbinAuthorizer`) read roles straight from mappers (`RoleMetaMapper.listRolesByUserId` / `listRolesByGroupId`), owner from its own `ownerRelCache` (which polls `owner_meta`), and id from its own `metadataIdCache`. It does not use the entity store relation cache at all. Relation caching was first added with authorization in mind, but authorization no longer uses it.
+
+**Cost of removing it.** Each call becomes one indexed query — not an N+1 (one query per item). No list endpoint loads relations per item in a loop. The one place a single request makes several queries is **tag / policy inheritance**: listing an object's tags also reads its parents (the object plus up to ~3 ancestors), so a tag lookup is up to ~4 single-row queries; the cache mainly saves re-reading popular parents. This is the only workload where removing the cache adds real DB load, and it can be measured today — those calls are already `@Monitored` (`baseMetricName = "listTagsForMetadataObject"`, `"getOwner"`, `"listPoliciesForMetadataObject"`).
+
+**Decision.** Remove relation caching from the entity store cache. Relation reads go straight to the DB (one indexed query each), the same as authorization already does. This is safe for the core read path and for authorization; the only risk is workloads with heavy tag/policy inheritance reads, which we can watch with the existing metrics and, if ever needed, address by adding precise relation caching back later.
+
+The result: the cache holds only **entity keys**, so cross-node invalidation becomes the easy one-to-one case, and (as both implementations show) each design loses its hardest part. The `ReverseIndexCache` and the two-direction relation keys are removed with it.
+
+But "cache only entity keys" is not the end of it: some entities **copy fields from other entities**, which would bring the reverse-lookup problem back. The next section works out which entities are actually safe to cache.
+
+---
+
+## Which Entities to Cache
+
+Dropping relations leaves the entity keys. But not every entity key is truly one-to-one. Some entities store fields **copied from other entities**, and those copies go stale when the other entity changes — which brings back the same reverse lookup we just removed. So we look at what each cached entity actually holds.
+
+**Self-contained vs. derived.**
+
+| Entity | Copies a field from another entity? | Safe to cache on its own? |
+| ------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------- |
+| metalake, catalog, schema, table, topic, model, view, fileset | no — holds only its own data (columns, properties, comment…) | yes |
+| tag, policy | no — associations are relations, not stored on the entity | yes |
+| user, group | yes — `roleNames` / `roleIds`, built from the user's roles | no |
+| role | yes — `securableObjects`, built from metadata objects | no |
+
+**Why user / group / role are a problem.**
+
+- `getUserByIdentifier` builds `roleNames` at read time by joining the user's roles (`UserMetaService` calls `RoleMetaService.listRolesByUserId`). If a role is dropped, it disappears from every user's list, but the user rows are not touched — so a cached user still lists the dropped role. Finding which users hold a role is a reverse lookup (role → users), exactly what dropping relations was meant to avoid.
+- `RoleEntity.securableObjects` has the same shape one level up: if a metadata object is renamed or dropped, a cached role that points at it is stale, and finding which roles point at an object is again a reverse lookup (object → roles).
+
+**Does authorization need these in the cache?** This is the key question, because authorization is the hot path. We checked `JcasbinAuthorizer`:
+
+- **user / group — no.** It reads user and group data through its own mappers (`UserMetaMapper`, `GroupMetaMapper`) into its own caches (`userRoleCache`, `groupRoleCache`), never through the entity store cache. So excluding user/group from the entity store cache does not affect authorization at all.
+- **role — only at cold start or after a change.** It does read role entities through the entity store (`entityStore.batchGet/get(ROLE)`), but only to (re)load a role's policies into the enforcer. Loaded roles are held in `loadedRoles`, a cache with `expireAfterAccess` (default 1 hour), so a role used at least once an hour never expires and the entity read is skipped. The entity read happens only on cold start, right after a role is edited, or after a role sits unused for over an hour — each a cheap one-time `batchGet`, not a per-request cost.
+
+So caching user, group, and role buys almost nothing (authorization does not depend on it) and costs a lot (the reverse-lookup problem comes back). tag and policy are safe to cache, but they are low-volume governance objects, not the read-heavy metadata the cache exists for.
+
+**Conclusion: cache only the basic metadata objects** — metalake, catalog, schema, table, topic, model, view, fileset. In code this is a small allowlist of entity types in the cache. Every cached entity is then self-contained and one-to-one, so cross-node invalidation stays precise with no reverse lookups. As a bonus, these entities already write ALTER/DROP rows to `entity_change_log`, so the writer side needs no change at all.
+
+The cache now holds only self-contained metadata objects. The next question is how to tell the other nodes to drop a key when it changes.
+
+---
+
+## Approaches to Multi-Node Consistency
+
+Keeping a per-node cache fresh across a cluster is a common problem: after a write on one node, no other node may serve stale data. The standard techniques:
+
+| Approach | How it works | Trade-off |
+| -------------------------- | ------------------------------------------------------------------------------------------- |------------------------------------------------------------------------------------|
+| TTL only | each entry expires after a fixed time | no work, but every node serves old data until the TTL passes |
+| Pub/sub broadcast | the writer sends "invalidate X"; every node subscribes | low delay, but needs a message bus and must handle missed messages |
+| Change-log table + poller | the writer records the change in a DB table in the same transaction; each node polls it | no new infrastructure (reuses the DB), survives restarts; up to one poll of delay |
+| Shared (distributed) cache | one copy for the whole cluster, so there is nothing per-node to keep fresh | no propagation at all, but needs Redis/Memcached and a network round-trip per read |
+
+### How other metadata systems solve it
+
+We looked at how similar systems keep **their own per-node cache** coherent across a cluster (not how they notify downstream/derived systems — that is a different problem). **The most common answer is a per-node cache kept fresh by polling or by an invalidation/broadcast signal; no one relies on plain TTL.** Each row below has a source:
+
+| System | How it keeps its per-node cache fresh across nodes | Technique |
+| ---------------------------------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------|
+| **Hive Metastore** (`CachedStore`) | each node's in-memory cache is updated by a background thread that **polls the `NOTIFICATION_LOG` table** (written by `DbNotificationListener`); the log is in commit order and is the source of truth, and reads fall back to the DB until the thread catches up [1][2] | change-log + poll |
+| **Apache Ranger** (plugins) | each plugin keeps a **local policy cache** and **periodically polls Ranger Admin** for a newer version (default every 30s, `policy.pollIntervalMs`), downloading only the delta when the version changes [3] | periodic poll |
+| **Confluent Schema Registry** | one compacted Kafka topic **`_schemas`** is the commit log and the source of truth; every node reads it in a background thread to build its **local materialized view** [4] | shared log |
+| **Apache Impala** (`catalogd`) | metadata changes are **broadcast to all coordinators through `statestored`**; in local-catalog mode coordinators instead **fetch on demand and cache locally**, and invalidate that cache on `catalogd` failover [5] | broadcast / on-demand pull |
+| **Redis** (client-side caching) | with `CLIENT TRACKING` the server remembers which keys each client cached and **pushes an invalidation message** (RESP3 push) when a key changes, so the client flushes its local copy [6] | server-push invalidation |
Review Comment:
The numeric citations in the comparison table don’t match the “Sources” list: the table references [3]..[8], but the sources list only defines 1..7 and the mapping is inconsistent (e.g., table’s [3] is Ranger, but source 3 is Schema Registry). This makes the citations unreliable; please renumber and/or update the sources list so each reference used in the table resolves to the intended source.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3557521208
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -252,10 +252,55 @@ The entity store cache becomes a third consumer of the poller, next to the catal
### Consistency
+The cache is never the source of truth. The write path always reads the DB under the optimistic version lock, so eventual consistency can **never** cause a lost update or corrupt data. Its only observable effect is **bounded read staleness on non-writing nodes**: for up to one poll interval, a node other than the writer may serve an older value.
+
- **Other nodes:** eventual — an entity key is dropped within one poll interval of the change.
- **Writing node:** unchanged — it still clears its own cache on the write path, so it reads its own writes right away. Its own row is replayed later, which does nothing (clearing an already-clear key is a no-op).
- **Write path:** unchanged — it reads the DB with the optimistic version check.
+The rest of this section works through every way that staleness window can be observed, and how each is handled.
+
+#### Staleness scenarios and mitigations
+
+**1. Plain stale read (bounded, mostly tolerable).**
+
+| # | Scenario | Effect | Possible mitigation |
+| - | -------------------------------------------------------------- |-----------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------|
+| 1 | Node A ALTERs a table (add column); B GETs it | B serves the old schema for up to one poll interval | Accept within the SLA window; a caller that needs an exact schema uses a consistent (cache-bypass) read |
+| 2 | Node A DROPs a table; B GETs it | B still reports it as present (cache hit) until the next poll | Accept — any write to it on B is re-validated against the DB and rejected as not-found, so no corruption |
+| 3 | RENAME (the old name behaves like a DROP); B GETs the old name | B keeps resolving the old name until the next poll; the new name misses → DB load | Same as DROP — bounded by the poll interval |
+| 4 | A property changes (e.g. Iceberg metadata-location); B GETs it | B returns the old location → a query on B may read an old snapshot/path | Highest-value case: offer a consistent (cache-bypass) read for location-sensitive callers, or use `redis` |
+
+**2. Read-your-writes across nodes.**
+
+| # | Scenario | Effect | Possible mitigation |
+| - |---------------------------------------------------------------------|-------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
+| 5 | Through a load balancer, ALTER on A then an immediate read on B | Stale — violates session consistency; without sticky routing the change looks lost | Sticky sessions at the LB, or a client-supplied last-seen version that bypasses the cache when the copy is older; `redis` removes it entirely |
+| 6 | CREATE (rather than ALTER/DROP) | No problem — no negative caching and `list` skips the cache, so a new entity is visible at once | None needed |
+
+**3. Cross-node read-modify-write.**
+
+| # | Scenario | Effect | Possible mitigation |
+| - | ------------------------------------------------------------------------------------- |-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------|
+| 7 | B reads stale value A and submits an update carrying A's version as the expected one | The optimistic lock rejects it on version mismatch — safe, but the user sees an unexpected conflict | Accept (correctness is preserved); reduce its frequency with the read-your-writes mitigations above |
+
+**4. Is the window actually bounded? — poller reliability (the real risk).** The "at most one poll interval" guarantee holds **only if the poller never drops a row**. If it does, the stale entry survives until the cache TTL, so this is the one place eventual consistency itself can break.
+
+| # | Scenario | Effect | Possible mitigation |
+| -- |-----------------------------------------------------------------------------------------------------------|-----------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------|
+| 8 | Commit-ordering gap / a skipped row | The key is never invalidated; stale until the TTL | Reuse the lag-safe, id-based polling already built for the change log (`#11736`); keep the cache TTL as a backstop |
+| 9 | Poller thread dies / DB briefly unreachable | That node serves stale data until the TTL | TTL backstop + monitor poller liveness/lag and alert |
+| 10 | Hierarchical DROP: only the container (schema) emits a row; children are cleared by a forward prefix scan | Correct as long as the prefix scan covers every child key | Cover with the hierarchical-drop test; confirm no child is written in a separate transaction that outlives the container row |
+
+**5. Idempotency (no issue).** Replaying ALTER then DROP, in any order or duplicated, is safe: invalidation is idempotent, so out-of-order or repeated replay has no effect.
+
+#### Summary: main risks, resolutions, and the staleness SLA
+
+- **Correctness is never at stake.** The DB plus the optimistic version lock stay authoritative; the worst a stale read can do is surface a bounded-old value (scenarios 1–4) or an unexpected conflict (scenario 7), never a lost update or corruption.
Review Comment:
One scenario is the modification scenario. If we read the stale data, and this stale data will not raise the exception when querying, and will implicitly return a wrong value, this could be a big problem.
If the modification throws an exception when querying, then the stale data should be safe.
I think you need to think about this problem, and clarify it as much as you can.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3584257977
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -0,0 +1,412 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+---
+title: "Multi-Node Support for the Entity Store Cache"
+status: "Draft"
+date: "2026-07-07"
+---
+
+## Background
+
+Gravitino has two caches:
+
+- The **jcasbin authorization cache** already works with more than one node.
+- The **entity store cache** does not. When a change happens on node A, only node A clears its cache. Node B keeps serving the old data until its entry expires.
+
+Because of this, the only safe way to run more than one node today is to turn the entity store cache off (`gravitino.cache.enabled=false`). That is bad for read-heavy catalogs, especially Iceberg.
+
+This document proposes a design to make the entity store cache correct when running more than one node. It is a design proposal; no behavior has changed yet.
+
+## Goals and Non-Goals
+
+**Goals**
+
+- Make the entity store cache correct with more than one node, so `gravitino.cache.enabled=true` is safe.
+- Keep the cache **pluggable**: one SPI, chosen by `gravitino.cache.impl`. Ship `caffeine` as the default (no extra dependency) and `redis` as an option the user turns on by config. The current caffeine implementation is rather complex for any users to make any an new implementation, so we need to simplify it.
+- Keep single-node behavior and the write path (the optimistic version lock) unchanged.
+
+**Non-Goals**
+
+- Replace the entity store or its write path. The cache sits in front of the store and is never the source of truth.
+- Add a cluster membership / gossip layer or any other complex distributed system. We only use the DB Gravitino already needs, or the external cache the user turns on.
+
+---
+
+## Current Cache Implementation
+
+`EntityCache` is already an SPI, chosen by `gravitino.cache.impl` and created by `CacheFactory`. There is one implementation today, `CaffeineEntityCache` (`caffeine`): an in-memory cache, **one copy per node**, with two kinds of entries:
+
+- **entity keys** `(ident, type)` → the entity itself;
+- **relation keys** `(ident, type, relType)` → the list of related entities, stored **in both directions** and kept in step by an in-process **reverse index** (`ReverseIndexCache`).
+
+On a write, the node clears the changed key and then uses the reverse index to clear the related keys. On a single node this is correct. The problem is that this clearing happens **only on the node that made the change** (`RelationalEntityStore` calls `cache.invalidate(...)` locally). Nothing tells the other nodes, so they serve old data until their entries expire.
+
+Some behavior is already safe with more than one node and does not change:
+
+| Already correct | Why |
+| ------------------------- | ---------------------------------------------------------------------------- |
+| Writes never lose updates | The write path reads the DB (not the cache) with an optimistic version check |
+| `list(namespace)` | Skips the cache, so it is never stale |
+| CREATE | Needs nothing: no negative caching, and `list` skips the cache |
+
+The rest of the problem splits in two:
+
+- **entity keys** are one-to-one. "table T changed" names exactly the key to drop, and any node can drop it. This is easy.
+- **relation keys** have a reverse key. Dropping one side (say a role) also means dropping the other side's key (each user that had the role), but "the role changed" does not say *which* users those are. The writing node knows them from its local reverse index; a remote node may not.
+
+That reverse key is the hard part. So the first question is whether the cache needs relations at all.
+
+---
+
+## Do We Need to Cache Relations?
+
+All the cross-node difficulty comes from relation caching (the reverse key and the write fan-out). Before building around it, we checked whether it is actually important for performance. It is not.
+
+**Who reads the relation cache.** The cached relation path is `RelationalEntityStore.listEntitiesByRelation`, which runs **one indexed SQL join** per call (`JDBCBackend.listEntitiesByRelation`). Its callers are all metadata governance managers:
+
+| Caller | Relation | API that uses it |
+| -------------------- | ---------------------------- |-----------------------------------|
+| `OwnerManager` | `OWNER_REL` | `GET .../owner` |
+| `RoleManager` | role relations | role / authorization management |
+| `FutureGrantManager` | role/user/group relations | applying future grants (admin op) |
+| `TagManager` | `TAG_METADATA_OBJECT_REL` | tag endpoints |
+| `PolicyManager` | `POLICY_METADATA_OBJECT_REL` | policy endpoints |
+
+**Who does not.** The two paths that must be fast do **not** use it:
+
+- **Core metadata reads** (`get` / `list` of table, schema, catalog, …) never call `listEntitiesByRelation`. Removing the relation cache does not affect them at all.
+- **Authorization checks** (`JcasbinAuthorizer`) read roles straight from mappers (`RoleMetaMapper.listRolesByUserId` / `listRolesByGroupId`), owner from its own `ownerRelCache` (which polls `owner_meta`), and id from its own `metadataIdCache`. It does not use the entity store relation cache at all. Relation caching was first added with authorization in mind, but authorization no longer uses it.
+
+**Cost of removing it.** Each call becomes one indexed query — not an N+1 (one query per item). No list endpoint loads relations per item in a loop. The one place a single request makes several queries is **tag / policy inheritance**: listing an object's tags also reads its parents (the object plus up to ~3 ancestors), so a tag lookup is up to ~4 single-row queries; the cache mainly saves re-reading popular parents. This is the only workload where removing the cache adds real DB load, and it can be measured today — those calls are already `@Monitored` (`baseMetricName = "listTagsForMetadataObject"`, `"getOwner"`, `"listPoliciesForMetadataObject"`).
+
+**Decision.** Remove relation caching from the entity store cache. Relation reads go straight to the DB (one indexed query each), the same as authorization already does. This is safe for the core read path and for authorization; the only risk is workloads with heavy tag/policy inheritance reads, which we can watch with the existing metrics and, if ever needed, address by adding precise relation caching back later.
+
+The result: the cache holds only **entity keys**, so cross-node invalidation becomes the easy one-to-one case, and (as both implementations show) each design loses its hardest part. The `ReverseIndexCache` and the two-direction relation keys are removed with it.
+
+But "cache only entity keys" is not the end of it: some entities **copy fields from other entities**, which would bring the reverse-lookup problem back. The next section works out which entities are actually safe to cache.
+
+---
+
+## Which Entities to Cache
+
+Dropping relations leaves the entity keys. But not every entity key is truly one-to-one. Some entities store fields **copied from other entities**, and those copies go stale when the other entity changes — which brings back the same reverse lookup we just removed. So we look at what each cached entity actually holds.
+
+**Self-contained vs. derived.**
+
+| Entity | Copies a field from another entity? | Safe to cache on its own? |
+| ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
+| metalake, catalog, schema, table, topic, view, fileset | no — holds only its own data (columns, properties, comment…) | yes |
+| model, model version, function | no — but each holds a load-bearing pointer (the model version URI / latest version, or the function implementation) that goes stale on other nodes | no — left out for cross-node safety, see [Consistency](#consistency) |
+| tag, policy | no — associations are relations, not stored on the entity | yes |
+| user, group | yes — `roleNames` / `roleIds`, built from the user's roles | no |
+| role | yes — `securableObjects`, built from metadata objects | no |
+
+**Why user / group / role are a problem.**
+
+- `getUserByIdentifier` builds `roleNames` at read time by joining the user's roles (`UserMetaService` calls `RoleMetaService.listRolesByUserId`). If a role is dropped, it disappears from every user's list, but the user rows are not touched — so a cached user still lists the dropped role. Finding which users hold a role is a reverse lookup (role → users), exactly what dropping relations was meant to avoid.
+- `RoleEntity.securableObjects` has the same shape one level up: if a metadata object is renamed or dropped, a cached role that points at it is stale, and finding which roles point at an object is again a reverse lookup (object → roles).
+
+**Does authorization need these in the cache?** This is the key question, because authorization is the hot path. We checked `JcasbinAuthorizer`:
+
+- **user / group — no.** It reads user and group data through its own mappers (`UserMetaMapper`, `GroupMetaMapper`) into its own caches (`userRoleCache`, `groupRoleCache`), never through the entity store cache. So excluding user/group from the entity store cache does not affect authorization at all.
+- **role — only at cold start or after a change.** It does read role entities through the entity store (`entityStore.batchGet/get(ROLE)`), but only to (re)load a role's policies into the enforcer. Loaded roles are held in `loadedRoles`, a cache with `expireAfterAccess` (default 1 hour), so a role used at least once an hour never expires and the entity read is skipped. The entity read happens only on cold start, right after a role is edited, or after a role sits unused for over an hour — each a cheap one-time `batchGet`, not a per-request cost.
+
+So caching user, group, and role buys almost nothing (authorization does not depend on it) and costs a lot (the reverse-lookup problem comes back). tag and policy are safe to cache, but they are low-volume governance objects, not the read-heavy metadata the cache exists for.
+
+**Conclusion: cache only the basic metadata objects** — metalake, catalog, schema, table, topic, view, fileset. In code this is a small allowlist of entity types in the cache. Model, model version, and function are left out on purpose: they are read rarely, and each one holds a load-bearing pointer (the model version URI or latest version, or the function implementation) that would return a wrong answer on another node if it went stale — the per-alter check under [Consistency](#consistency) explains why. Every cached entity is then self-contained and one-to-one, so cross-node invalidation stays precise with no reverse lookups. As a bonus, these entities already write ALTER/DROP rows to `entity_change_log`, so the writer side needs no change at all.
+
+The cache now holds only self-contained metadata objects. The next question is how to tell the other nodes to drop a key when it changes.
+
+---
+
+## Approaches to Multi-Node Consistency
+
+Keeping a per-node cache fresh across a cluster is a common problem: after a write on one node, no other node may serve stale data. The standard techniques:
+
+| Approach | How it works | Trade-off |
+| -------------------------- | ------------------------------------------------------------------------------------------- |------------------------------------------------------------------------------------|
+| TTL only | each entry expires after a fixed time | no work, but every node serves old data until the TTL passes |
+| Pub/sub broadcast | the writer sends "invalidate X"; every node subscribes | low delay, but needs a message bus and must handle missed messages |
+| Change-log table + poller | the writer records the change in a DB table in the same transaction; each node polls it | no new infrastructure (reuses the DB), survives restarts; up to one poll of delay |
+| Shared (distributed) cache | one copy for the whole cluster, so there is nothing per-node to keep fresh | no propagation at all, but needs Redis/Memcached and a network round-trip per read |
+
+### How other metadata systems solve it
+
+We looked at how similar systems keep **their own per-node cache** coherent across a cluster (not how they notify downstream/derived systems — that is a different problem). **The most common answer is a per-node cache kept fresh by polling or by an invalidation/broadcast signal; no one relies on plain TTL.** Each row below has a source:
+
+| System | How it keeps its per-node cache fresh across nodes | Technique |
+| ---------------------------------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------|
+| **Hive Metastore** (`CachedStore`) | each node's in-memory cache is updated by a background thread that **polls the `NOTIFICATION_LOG` table** (written by `DbNotificationListener`); the log is in commit order and is the source of truth, and reads fall back to the DB until the thread catches up [1][2] | change-log + poll |
+| **Apache Ranger** (plugins) | each plugin keeps a **local policy cache** and **periodically polls Ranger Admin** for a newer version (default every 30s, `policy.pollIntervalMs`), downloading only the delta when the version changes [3] | periodic poll |
+| **Confluent Schema Registry** | one compacted Kafka topic **`_schemas`** is the commit log and the source of truth; every node reads it in a background thread to build its **local materialized view** [4] | shared log |
+| **Apache Impala** (`catalogd`) | metadata changes are **broadcast to all coordinators through `statestored`**; in local-catalog mode coordinators instead **fetch on demand and cache locally**, and invalidate that cache on `catalogd` failover [5] | broadcast / on-demand pull |
+| **Redis** (client-side caching) | with `CLIENT TRACKING` the server remembers which keys each client cached and **pushes an invalidation message** (RESP3 push) when a key changes, so the client flushes its local copy [6] | server-push invalidation |
+| **CockroachDB** | each node caches table/schema descriptors under a **versioned lease**; at most the **two latest versions** can be leased at once, and a schema change waits for old leases to be released or to expire (lease duration on the order of minutes) before advancing [7] | versioned lease |
+| **Trino** (Hive connector) | a coordinator-side metastore cache with a fixed **TTL plus background refresh** (`hive.metastore-cache-ttl`, `hive.metastore-refresh-interval`); its own docs note this can return stale data [8] | TTL + refresh |
+
+Two things stand out: **polling a change/version log (Hive, Ranger) is the most common, no-new-infrastructure answer**, and the one system that relies on **TTL alone (Trino) is documented to sometimes return stale data** — even CockroachDB, which looks TTL-like, actually uses bounded leases with active release, not plain expiry. That is exactly why TTL is not enough for us.
+
+### The two approaches we pick
+
+The closest match to what Gravitino needs is **Hive Metastore's `CachedStore`**: a per-node cache kept fresh by polling a change log in the same DB. Gravitino already has both pieces — the DB as the source of truth, and an `entity_change_log` table with a poller (built for the jcasbin cache). So this works with **no new infrastructure**. This is the default, and we call it `caffeine`.
+
+The broadcast / pub-sub-invalidation systems (Impala's `statestored`, Redis client-side caching, Schema Registry's shared log) work well, but they need a **message bus that Gravitino does not have**, so pub/sub is left for later (see the [roadmap](#roadmap)). **TTL alone** (Trino) is rejected for the stale-read reason its own docs give. That leaves two approaches that need no new component:
+
+- **reuse the DB** — a per-node cache kept fresh by the change log. → `caffeine`
+- **use a shared copy** — for teams already running Redis and wanting strong consistency, keep one copy in Redis. → `redis`
+
+**Sources**
+
+1. Hive — *Synchronized Metastore Cache*: <https://cwiki.apache.org/confluence/display/Hive/Synchronized+Metastore+Cache> (and HIVE-18661: <https://issues.apache.org/jira/browse/HIVE-18661>)
+2. Hive — `CachedStore.java` / `DbNotificationListener.java`: <https://github.com/apache/hive/blob/master/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/cache/CachedStore.java>
+3. Apache Ranger — *FAQ* (plugins cache policies locally and poll Ranger Admin at intervals): <https://ranger.apache.org/faq.html>; default `pollIntervalMs = 30000` in the plugin config: <https://github.com/apache/ranger/blob/master/hive-agent/conf/ranger-hive-security.xml>
+4. Confluent Schema Registry docs: <https://docs.confluent.io/platform/current/schema-registry/index.html>
+5. Apache Impala — *Metadata Management* (catalogd broadcasts via statestored; local-catalog mode fetches on demand and caches): <https://impala.apache.org/docs/build/html/topics/impala_metadata.html>
+6. Redis — *Client-side caching* / `CLIENT TRACKING` (RESP3 push invalidation): <https://redis.io/docs/latest/develop/reference/client-side-caching/>
+7. CockroachDB — *Table Descriptor Lease* RFC (at most two leased versions; ~5m lease): <https://github.com/cockroachdb/cockroach/blob/master/docs/RFCS/20151009_table_descriptor_lease.md> (and *Online Schema Changes*: <https://www.cockroachlabs.com/docs/stable/online-schema-changes>)
+8. Trino — *Metastores* docs: <https://trino.io/docs/current/object-storage/metastores.html> (stale-read note: <https://github.com/trinodb/trino/issues/10512>)
+
+---
+
+## The Pluggable Framework
+
+We now have two approaches that behave differently — one keeps a local copy per node, the other keeps one shared copy. To let a user pick either one by config, the cache stays **pluggable**, and each implementation says which kind it is. The `EntityCache` SPI adds one method:
+
+```
+EntityCache.coherence() → LOCAL_PER_NODE | SHARED
+```
+
+- `LOCAL_PER_NODE` — each node has its own copy, so a write must be **sent to the other nodes** to clear their copies. `caffeine` is this kind.
+- `SHARED` — one copy for the whole cluster, so a write clears it once and every node sees it. Nothing to send. `redis` is this kind.
+
+The write path is the same for both; only what happens after the local clear differs, and that is decided by `coherence()`:
+
+<!-- diagram source: diagrams/coherence-gate.mmd (regenerate with mermaid-cli) -->
+
+
+`CacheFactory.ENTITY_CACHES` is already a name → class table loaded by reflection, so adding `redis` next to `caffeine` is one new table entry with no change to the callers.
+
+The rest of this document describes each implementation — first the default local cache, then the shared cache.
+
+---
+
+# Implementation A — Caffeine (`caffeine`, `LOCAL_PER_NODE`, default)
+
+With only self-contained metadata objects cached, "entity X changed" names exactly the key to drop, and **any node can drop it** — no reverse key, no fan-out. The channel to carry "entity X changed" to the other nodes already exists and is already used by other caches.
+
+<!-- diagram source: diagrams/entity-key-invalidation.mmd (regenerate with mermaid-cli) -->
+
+
+### Reuse the existing transport
+
+`entity_change_log` and `EntityChangeLogPoller` already exist and are already used by two consumers:
+
+- `CatalogChangeLogListener` → clears `CatalogManager`'s catalog cache;
+- `JcasbinChangeListener` → clears jcasbin's **id-mapping cache** (`metadataIdCache`).
+
+Each row is `{metalake, entity_type, full_name, operate_type (ALTER | DROP), created_at}`. The structural MetaServices (metalake, catalog, schema, table, topic, view, fileset) already write a row on ALTER/DROP. We add the entity store cache as a **third consumer** of the same poller.
+
+### Writer side
+
+The cache now holds only metadata objects, and those **already write** an ALTER/DROP row to `entity_change_log` today. So the writer side needs **no change** — no new rows, no new columns, no new operate type:
+
+| Change | Cached? | Writes a change-log row |
+| ----------------------------------------------------- | ------- | ----------------------- |
+| structural ALTER/DROP (table, schema, catalog, …) | yes | yes — already emitted |
+| user / group / role / tag / policy ALTER/DROP | no | not needed (not cached) |
+| model / model version / function ALTER/DROP | no | not needed (not cached) |
+| relation change (grant, set owner, attach tag/policy) | no | not needed (not cached) |
+
+The existing structural rows are written in the same transaction as the entity write, so nothing new is added here.
+
+### Reader side
+
+A new `EntityChangeLogListener` for the entity store cache runs on the **same poller** and replays each row as a direct invalidation:
+
+```
+onEntityChange(rows):
+ for row in rows:
+ cache.invalidate(identOf(row), row.entity_type) # drop exactly this entity key
+```
+
+Dropping a container (for example a schema) must also drop its cached children. That uses the **forward** prefix scan the cache already has (`cacheIndex`), on the local node — the reverse index is not involved. This is the only remaining cascade.
+
+### A third consumer of the existing feed
+
+The entity store cache becomes a third consumer of the poller, next to the catalog cache and the jcasbin id-mapping cache. All three read the same structural ALTER/DROP rows that already exist — the entity store cache clears its entity key, the catalog cache clears its catalog, jcasbin clears its id mapping. There is no new row type, so the existing consumers do not change.
+
+### Consistency
+
+The cache never holds the truth. Every write goes to the DB first, under the version lock, so a stale cache can **never** cause a lost update or a bad write. The only thing that can go wrong is that a read on **another node** returns an old value for a short time — at most one poll interval, until that node drops the key.
+
+So the real question is simple: when another node reads an old value, does it matter? We went through every alter and every drop, for every cached entity, one at a time. A stale read falls into one of two buckets:
+
+- **The old value makes the next step fail with an error.** The user sees the error and tries again. This is safe.
+- **The old value is used silently and gives a wrong answer, with no error.** This is the dangerous kind.
+
+We only need to worry about the second bucket.
+
+#### Two groups of cached entities
+
+The danger depends on where the real data comes from.
+
+**Group 1 — the data comes from the connector: table, view, topic, and schemas in external catalogs.** For these, Gravitino does not read the metadata from its own cache. On every load it asks the underlying system (Hive, Iceberg, JDBC, Kafka) for the current object, and uses the cached entity only for Gravitino's own id and audit fields. All nodes ask the same underlying system, so they all see the same thing. If the object was dropped or renamed, the connector call fails right away with a "not found" error. **This whole group is safe — nothing to do.**
+
+**Group 2 — the data comes from Gravitino's own store: metalake, catalog, managed schema, fileset, model, model version, function.** Here the cached entity *is* the answer, so a stale read really can return an old value. We looked at each alter in this group.
+
+(Views follow the same rule as tables: their definition is read through the connector on every load, so they sit in Group 1 and are safe.)
+
+#### Walking through the alters in Group 2
+
+Most alters are safe:
+
+| Change | What a stale read does | Safe? |
+| -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ----- |
+| rename (metalake, catalog, schema, fileset, model) | reading the old name returns a leftover copy, but any write to it goes to the DB and fails; the new name misses the cache and loads fresh from the DB | yes |
+| update comment | you see an old comment for a moment | yes |
+| set / remove property (metalake, model, fileset) | these properties do not change where the data lives | yes |
+| fileset storage location | **cannot be changed** — there is no alter for it, so it can never go stale | yes |
+| drop | for Group 1 the connector call fails; for a fileset the file path is gone and access fails | yes |
+| catalog changes | already handled today by a separate cross-node signal (`CatalogChangeLogListener`), not by this cache | yes |
+
+Five cases are **not** safe — a stale read gives a wrong answer with no error. They are in the model area, functions, or the metalake on/off flag:
+
+| Change | Why a stale read is wrong, with no error |
+| --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| model version — update / add / remove URI | the URI points to the model files. An old URI silently loads the **wrong model files**. |
+| model version — update aliases | an alias silently points to the **wrong version**. |
+| model — latest version (after a new version is added on another node) | "get the latest version" silently returns an **old version**. |
+| function — add / update / remove implementation or definition | the implementation is the code the function runs. An old copy silently runs the **wrong function code**. |
+| metalake — disable | a node with a stale copy still thinks the metalake is on and **lets operations run** on a metalake that was turned off. (Turning it back on is safe: a stale node only throws "in use" by mistake.) |
+
+#### What we do about it
+
+We keep the simple design and remove the danger at the source:
+
+- **Do not cache the model area (model, model version) or functions.** The cache exists for the read-heavy path, which today is tables; model and function reads are a small share of traffic, so reading them from the DB every time costs almost nothing. Leaving these areas out removes four of the five dangerous cases outright and keeps the rule simple (an entity type is either in or out — no half-cached entity with a version-checked pointer). These reads are then always fresh, on every node. If model or function traffic grows later, we can add them back with a proper freshness check.
+- **Read the metalake on/off flag straight from the DB, not the cache.** This is a cheap single-row read on the guard check only, and it removes the last dangerous case.
Review Comment:
I'm not so sure about this point. Reading it from databases every time is not so efficient, and we need to come up with a better plan for it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "yuqi1129 (via GitHub)" <gi...@apache.org>.
yuqi1129 commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3595468952
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -225,16 +225,17 @@ Each row is `{metalake, entity_type, full_name, operate_type (ALTER | DROP), cre
### Writer side
-The cache now holds only metadata objects, and those **already write** an ALTER/DROP row to `entity_change_log` today. So the writer side needs **no change** — no new rows, no new columns, no new operate type:
+Most cached objects **already write** an ALTER/DROP row to `entity_change_log` today, so the writer side is almost unchanged — no new columns and no new operate type. The one addition is a change-log row for **tag and policy**, which are cached but do not emit one yet:
-| Change | Cached? | Writes a change-log row |
-| ----------------------------------------------------- | ------- | ----------------------- |
-| structural ALTER/DROP (table, schema, catalog, …) | yes | yes — already emitted |
-| user / group / role / tag / policy ALTER/DROP | no | not needed (not cached) |
-| model / model version / function ALTER/DROP | no | not needed (not cached) |
-| relation change (grant, set owner, attach tag/policy) | no | not needed (not cached) |
+| Change | Cached? | Writes a change-log row |
+| ----------------------------------------------------- | ------- | ------------------------------------- |
+| structural ALTER/DROP (table, schema, catalog, …) | yes | yes — already emitted |
+| tag / policy ALTER/DROP | yes | **add a new emit point** (none today) |
+| user / group / role ALTER/DROP | no | not needed (not cached) |
+| model / model version / function ALTER/DROP | no | not needed (not cached) |
+| relation change (grant, set owner, attach tag/policy) | no | not needed (not cached) |
-The existing structural rows are written in the same transaction as the entity write, so nothing new is added here.
+The existing structural rows are written in the same transaction as the entity write; the new tag/policy rows must be written the same way, in the same transaction as the tag/policy write.
Review Comment:
I see. Since the work on tag-based access control is on the way, we need to rethink whether it's proper to use all relations from the entity cache. If we indeed decide to drop them all, alternatives should be provided for tag relations.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [#11923] docs(core): add multi-node entity store cache invalidation design [gravitino]
Posted by "jerryshao (via GitHub)" <gi...@apache.org>.
jerryshao commented on code in PR #11738:
URL: https://github.com/apache/gravitino/pull/11738#discussion_r3544002483
##########
design-docs/gravitino-entity-cache-multinode-design.md:
##########
@@ -0,0 +1,350 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+---
+title: "Multi-Node Support for the Entity Store Cache"
+status: "Draft"
+date: "2026-07-07"
+---
+
+## Background
+
+Gravitino has two caches:
+
+- The **jcasbin authorization cache** already works with more than one node.
+- The **entity store cache** does not. When a change happens on node A, only node A clears its cache. Node B keeps serving the old data until its entry expires.
+
+Because of this, the only safe way to run more than one node today is to turn the entity store cache off (`gravitino.cache.enabled=false`). That is bad for read-heavy catalogs, especially Iceberg.
+
+This document proposes a design to make the entity store cache correct when running more than one node. It is a design proposal; no behavior has changed yet.
+
+## Goals and Non-Goals
+
+**Goals**
+
+- Make the entity store cache correct with more than one node, so `gravitino.cache.enabled=true` is safe.
+- Keep the cache **pluggable**: one SPI, chosen by `gravitino.cache.impl`. Ship `caffeine` as the default (no extra dependency) and `redis` as an option the user turns on by config.
+- Keep single-node behavior and the write path (the optimistic version lock) unchanged.
+
+**Non-Goals**
+
+- Replace the entity store or its write path. The cache sits in front of the store and is never the source of truth.
+- Add a cluster membership / gossip layer or any other complex distributed system. We only use the DB Gravitino already needs, or the external cache the user turns on.
+
+---
+
+## Current Cache Implementation
+
+`EntityCache` is already an SPI, chosen by `gravitino.cache.impl` and created by `CacheFactory`. There is one implementation today, `CaffeineEntityCache` (`caffeine`): an in-memory cache, **one copy per node**, with two kinds of entries:
+
+- **entity keys** `(ident, type)` → the entity itself;
+- **relation keys** `(ident, type, relType)` → the list of related entities, stored **in both directions** and kept in step by an in-process **reverse index** (`ReverseIndexCache`).
+
+On a write, the node clears the changed key and then uses the reverse index to clear the related keys. On a single node this is correct. The problem is that this clearing happens **only on the node that made the change** (`RelationalEntityStore` calls `cache.invalidate(...)` locally). Nothing tells the other nodes, so they serve old data until their entries expire.
+
+Some behavior is already safe with more than one node and does not change:
+
+| Already correct | Why |
+| ------------------------- | ---------------------------------------------------------------------------- |
+| Writes never lose updates | The write path reads the DB (not the cache) with an optimistic version check |
+| `list(namespace)` | Skips the cache, so it is never stale |
+| CREATE | Needs nothing: no negative caching, and `list` skips the cache |
+
+The rest of the problem splits in two:
+
+- **entity keys** are one-to-one. "table T changed" names exactly the key to drop, and any node can drop it. This is easy.
+- **relation keys** have a reverse key. Dropping one side (say a role) also means dropping the other side's key (each user that had the role), but "the role changed" does not say *which* users those are. The writing node knows them from its local reverse index; a remote node may not.
+
+That reverse key is the hard part. So the first question is whether the cache needs relations at all.
+
+---
+
+## Do We Need to Cache Relations?
+
+All the cross-node difficulty comes from relation caching (the reverse key and the write fan-out). Before building around it, we checked whether it is actually important for performance. It is not.
+
+**Who reads the relation cache.** The cached relation path is `RelationalEntityStore.listEntitiesByRelation`, which runs **one indexed SQL join** per call (`JDBCBackend.listEntitiesByRelation`). Its callers are all metadata governance managers:
+
+| Caller | Relation | API that uses it |
+| -------------------- | ---------------------------- |-----------------------------------|
+| `OwnerManager` | `OWNER_REL` | `GET .../owner` |
+| `RoleManager` | role relations | role / authorization management |
+| `FutureGrantManager` | role/user/group relations | applying future grants (admin op) |
+| `TagManager` | `TAG_METADATA_OBJECT_REL` | tag endpoints |
+| `PolicyManager` | `POLICY_METADATA_OBJECT_REL` | policy endpoints |
+
+**Who does not.** The two paths that must be fast do **not** use it:
+
+- **Core metadata reads** (`get` / `list` of table, schema, catalog, …) never call `listEntitiesByRelation`. Removing the relation cache does not affect them at all.
+- **Authorization checks** (`JcasbinAuthorizer`) read roles straight from mappers (`RoleMetaMapper.listRolesByUserId` / `listRolesByGroupId`), owner from its own `ownerRelCache` (which polls `owner_meta`), and id from its own `metadataIdCache`. It does not use the entity store relation cache at all. Relation caching was first added with authorization in mind, but authorization no longer uses it.
+
+**Cost of removing it.** Each call becomes one indexed query — not an N+1 (one query per item). No list endpoint loads relations per item in a loop. The one place a single request makes several queries is **tag / policy inheritance**: listing an object's tags also reads its parents (the object plus up to ~3 ancestors), so a tag lookup is up to ~4 single-row queries; the cache mainly saves re-reading popular parents. This is the only workload where removing the cache adds real DB load, and it can be measured today — those calls are already `@Monitored` (`baseMetricName = "listTagsForMetadataObject"`, `"getOwner"`, `"listPoliciesForMetadataObject"`).
+
+**Decision.** Remove relation caching from the entity store cache. Relation reads go straight to the DB (one indexed query each), the same as authorization already does. This is safe for the core read path and for authorization; the only risk is workloads with heavy tag/policy inheritance reads, which we can watch with the existing metrics and, if ever needed, address by adding precise relation caching back later.
+
+The result: the cache holds only **entity keys**, so cross-node invalidation becomes the easy one-to-one case, and (as both implementations show) each design loses its hardest part. The `ReverseIndexCache` and the two-direction relation keys are removed with it.
+
+But "cache only entity keys" is not the end of it: some entities **copy fields from other entities**, which would bring the reverse-lookup problem back. The next section works out which entities are actually safe to cache.
+
+---
+
+## Which Entities to Cache
+
+Dropping relations leaves the entity keys. But not every entity key is truly one-to-one. Some entities store fields **copied from other entities**, and those copies go stale when the other entity changes — which brings back the same reverse lookup we just removed. So we look at what each cached entity actually holds.
+
+**Self-contained vs. derived.**
+
+| Entity | Copies a field from another entity? | Safe to cache on its own? |
+| ------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------- |
+| metalake, catalog, schema, table, topic, model, view, fileset | no — holds only its own data (columns, properties, comment…) | yes |
+| tag, policy | no — associations are relations, not stored on the entity | yes |
+| user, group | yes — `roleNames` / `roleIds`, built from the user's roles | no |
+| role | yes — `securableObjects`, built from metadata objects | no |
+
+**Why user / group / role are a problem.**
+
+- `getUserByIdentifier` builds `roleNames` at read time by joining the user's roles (`UserMetaService` calls `RoleMetaService.listRolesByUserId`). If a role is dropped, it disappears from every user's list, but the user rows are not touched — so a cached user still lists the dropped role. Finding which users hold a role is a reverse lookup (role → users), exactly what dropping relations was meant to avoid.
+- `RoleEntity.securableObjects` has the same shape one level up: if a metadata object is renamed or dropped, a cached role that points at it is stale, and finding which roles point at an object is again a reverse lookup (object → roles).
+
+**Does authorization need these in the cache?** This is the key question, because authorization is the hot path. We checked `JcasbinAuthorizer`:
+
+- **user / group — no.** It reads user and group data through its own mappers (`UserMetaMapper`, `GroupMetaMapper`) into its own caches (`userRoleCache`, `groupRoleCache`), never through the entity store cache. So excluding user/group from the entity store cache does not affect authorization at all.
+- **role — only at cold start or after a change.** It does read role entities through the entity store (`entityStore.batchGet/get(ROLE)`), but only to (re)load a role's policies into the enforcer. Loaded roles are held in `loadedRoles`, a cache with `expireAfterAccess` (default 1 hour), so a role used at least once an hour never expires and the entity read is skipped. The entity read happens only on cold start, right after a role is edited, or after a role sits unused for over an hour — each a cheap one-time `batchGet`, not a per-request cost.
+
+So caching user, group, and role buys almost nothing (authorization does not depend on it) and costs a lot (the reverse-lookup problem comes back). tag and policy are safe to cache, but they are low-volume governance objects, not the read-heavy metadata the cache exists for.
+
+**Conclusion: cache only the basic metadata objects** — metalake, catalog, schema, table, topic, model, view, fileset. In code this is a small allowlist of entity types in the cache. Every cached entity is then self-contained and one-to-one, so cross-node invalidation stays precise with no reverse lookups. As a bonus, these entities already write ALTER/DROP rows to `entity_change_log`, so the writer side needs no change at all.
+
+The cache now holds only self-contained metadata objects. The next question is how to tell the other nodes to drop a key when it changes.
+
+---
+
+## Approaches to Multi-Node Consistency
+
+Keeping a per-node cache fresh across a cluster is a common problem: after a write on one node, no other node may serve stale data. The standard techniques:
+
+| Approach | How it works | Trade-off |
+| -------------------------- | ------------------------------------------------------------------------------------------- |------------------------------------------------------------------------------------|
+| TTL only | each entry expires after a fixed time | no work, but every node serves old data until the TTL passes |
+| Pub/sub broadcast | the writer sends "invalidate X"; every node subscribes | low delay, but needs a message bus and must handle missed messages |
+| Change-log table + poller | the writer records the change in a DB table in the same transaction; each node polls it | no new infrastructure (reuses the DB), survives restarts; up to one poll of delay |
+| Shared (distributed) cache | one copy for the whole cluster, so there is nothing per-node to keep fresh | no propagation at all, but needs Redis/Memcached and a network round-trip per read |
+
+### How other metadata systems solve it
+
+We looked at how similar systems keep **their own per-node cache** coherent across a cluster (not how they notify downstream/derived systems — that is a different problem). **The most common answer is a per-node cache kept fresh by polling or by an invalidation/broadcast signal; no one relies on plain TTL.** Each row below has a source:
+
+| System | How it keeps its per-node cache fresh across nodes | Technique |
+| ---------------------------------- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------|
+| **Hive Metastore** (`CachedStore`) | each node's in-memory cache is updated by a background thread that **polls the `NOTIFICATION_LOG` table** (written by `DbNotificationListener`); the log is in commit order and is the source of truth, and reads fall back to the DB until the thread catches up [1][2] | change-log + poll |
+| **Apache Ranger** (plugins) | each plugin keeps a **local policy cache** and **periodically polls Ranger Admin** for a newer version (default every 30s, `policy.pollIntervalMs`), downloading only the delta when the version changes [3] | periodic poll |
+| **Confluent Schema Registry** | one compacted Kafka topic **`_schemas`** is the commit log and the source of truth; every node reads it in a background thread to build its **local materialized view** [4] | shared log |
+| **Apache Impala** (`catalogd`) | metadata changes are **broadcast to all coordinators through `statestored`**; in local-catalog mode coordinators instead **fetch on demand and cache locally**, and invalidate that cache on `catalogd` failover [5] | broadcast / on-demand pull |
+| **Redis** (client-side caching) | with `CLIENT TRACKING` the server remembers which keys each client cached and **pushes an invalidation message** (RESP3 push) when a key changes, so the client flushes its local copy [6] | server-push invalidation |
+| **CockroachDB** | each node caches table/schema descriptors under a **versioned lease**; at most the **two latest versions** can be leased at once, and a schema change waits for old leases to be released or to expire (lease duration on the order of minutes) before advancing [7] | versioned lease |
+| **Trino** (Hive connector) | a coordinator-side metastore cache with a fixed **TTL plus background refresh** (`hive.metastore-cache-ttl`, `hive.metastore-refresh-interval`); its own docs note this can return stale data [8] | TTL + refresh |
+
+Two things stand out: **polling a change/version log (Hive, Ranger) is the most common, no-new-infrastructure answer**, and the one system that relies on **TTL alone (Trino) is documented to sometimes return stale data** — even CockroachDB, which looks TTL-like, actually uses bounded leases with active release, not plain expiry. That is exactly why TTL is not enough for us.
+
+### The two approaches we pick
+
+The closest match to what Gravitino needs is **Hive Metastore's `CachedStore`**: a per-node cache kept fresh by polling a change log in the same DB. Gravitino already has both pieces — the DB as the source of truth, and an `entity_change_log` table with a poller (built for the jcasbin cache). So this works with **no new infrastructure**. This is the default, and we call it `caffeine`.
+
+The broadcast / pub-sub-invalidation systems (Impala's `statestored`, Redis client-side caching, Schema Registry's shared log) work well, but they need a **message bus that Gravitino does not have**, so pub/sub is left for later (see the [roadmap](#roadmap)). **TTL alone** (Trino) is rejected for the stale-read reason its own docs give. That leaves two approaches that need no new component:
+
+- **reuse the DB** — a per-node cache kept fresh by the change log. → `caffeine`
+- **use a shared copy** — for teams already running Redis and wanting strong consistency, keep one copy in Redis. → `redis`
+
+**Sources**
+
+1. Hive — *Synchronized Metastore Cache*: <https://cwiki.apache.org/confluence/display/Hive/Synchronized+Metastore+Cache> (and HIVE-18661: <https://issues.apache.org/jira/browse/HIVE-18661>)
+2. Hive — `CachedStore.java` / `DbNotificationListener.java`: <https://github.com/apache/hive/blob/master/standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/cache/CachedStore.java>
+3. Apache Ranger — *FAQ* (plugins cache policies locally and poll Ranger Admin at intervals): <https://ranger.apache.org/faq.html>; default `pollIntervalMs = 30000` in the plugin config: <https://github.com/apache/ranger/blob/master/hive-agent/conf/ranger-hive-security.xml>
+4. Confluent Schema Registry docs: <https://docs.confluent.io/platform/current/schema-registry/index.html>
+5. Apache Impala — *Metadata Management* (catalogd broadcasts via statestored; local-catalog mode fetches on demand and caches): <https://impala.apache.org/docs/build/html/topics/impala_metadata.html>
+6. Redis — *Client-side caching* / `CLIENT TRACKING` (RESP3 push invalidation): <https://redis.io/docs/latest/develop/reference/client-side-caching/>
+7. CockroachDB — *Table Descriptor Lease* RFC (at most two leased versions; ~5m lease): <https://github.com/cockroachdb/cockroach/blob/master/docs/RFCS/20151009_table_descriptor_lease.md> (and *Online Schema Changes*: <https://www.cockroachlabs.com/docs/stable/online-schema-changes>)
+8. Trino — *Metastores* docs: <https://trino.io/docs/current/object-storage/metastores.html> (stale-read note: <https://github.com/trinodb/trino/issues/10512>)
+
+---
+
+## The Pluggable Framework
+
+We now have two approaches that behave differently — one keeps a local copy per node, the other keeps one shared copy. To let a user pick either one by config, the cache stays **pluggable**, and each implementation says which kind it is. The `EntityCache` SPI adds one method:
+
+```
+EntityCache.coherence() → LOCAL_PER_NODE | SHARED
+```
+
+- `LOCAL_PER_NODE` — each node has its own copy, so a write must be **sent to the other nodes** to clear their copies. `caffeine` is this kind.
+- `SHARED` — one copy for the whole cluster, so a write clears it once and every node sees it. Nothing to send. `redis` is this kind.
+
+The write path is the same for both; only what happens after the local clear differs, and that is decided by `coherence()`:
+
+<!-- diagram source: diagrams/coherence-gate.mmd (regenerate with mermaid-cli) -->
+
+
+`CacheFactory.ENTITY_CACHES` is already a name → class table loaded by reflection, so adding `redis` next to `caffeine` is one new table entry with no change to the callers.
+
+The rest of this document describes each implementation — first the default local cache, then the shared cache.
+
+---
+
+# Implementation A — Caffeine (`caffeine`, `LOCAL_PER_NODE`, default)
+
+With only self-contained metadata objects cached, "entity X changed" names exactly the key to drop, and **any node can drop it** — no reverse key, no fan-out. The channel to carry "entity X changed" to the other nodes already exists and is already used by other caches.
+
+<!-- diagram source: diagrams/entity-key-invalidation.mmd (regenerate with mermaid-cli) -->
+
+
+### Reuse the existing transport
+
+`entity_change_log` and `EntityChangeLogPoller` already exist and are already used by two consumers:
+
+- `CatalogChangeLogListener` → clears `CatalogManager`'s catalog cache;
+- `JcasbinChangeListener` → clears jcasbin's **id-mapping cache** (`metadataIdCache`).
+
+Each row is `{metalake, entity_type, full_name, operate_type (ALTER | DROP), created_at}`. The structural MetaServices (metalake, catalog, schema, table, topic, model, view, fileset) already write a row on ALTER/DROP. We add the entity store cache as a **third consumer** of the same poller.
+
+### Writer side
+
+The cache now holds only metadata objects, and those **already write** an ALTER/DROP row to `entity_change_log` today. So the writer side needs **no change** — no new rows, no new columns, no new operate type:
+
+| Change | Cached? | Writes a change-log row |
+| ----------------------------------------------------- | ------- | ----------------------- |
+| structural ALTER/DROP (table, schema, catalog, …) | yes | yes — already emitted |
+| user / group / role / tag / policy ALTER/DROP | no | not needed (not cached) |
+| relation change (grant, set owner, attach tag/policy) | no | not needed (not cached) |
+
+The existing structural rows are written in the same transaction as the entity write, so nothing new is added here.
+
+### Reader side
+
+A new `EntityChangeLogListener` for the entity store cache runs on the **same poller** and replays each row as a direct invalidation:
+
+```
+onEntityChange(rows):
+ for row in rows:
+ cache.invalidate(identOf(row), row.entity_type) # drop exactly this entity key
+```
+
+Dropping a container (for example a schema) must also drop its cached children. That uses the **forward** prefix scan the cache already has (`cacheIndex`), on the local node — the reverse index is not involved. This is the only remaining cascade.
+
+### A third consumer of the existing feed
+
+The entity store cache becomes a third consumer of the poller, next to the catalog cache and the jcasbin id-mapping cache. All three read the same structural ALTER/DROP rows that already exist — the entity store cache clears its entity key, the catalog cache clears its catalog, jcasbin clears its id mapping. There is no new row type, so the existing consumers do not change.
+
+### Consistency
+
+- **Other nodes:** eventual — an entity key is dropped within one poll interval of the change.
Review Comment:
Is this eventual consistency acceptable?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@gravitino.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org