Build a high-availability metadata catalog for data lakes with snapshot isolation: read/write paths, caching layers, multi-region replication, and repair tooling.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We are building a high-availability metadata catalog for data lakes. This implies we need to handle:
Snapshot isolation: so that readers see a consistent snapshot even while writers are updating.
Multi-region replication: for high availability and disaster recovery.
Read and write paths: with appropriate caching layers to reduce latency and load.
Repair tooling: to handle inconsistencies and recover from failures.
We'll design a system based on a common pattern: a primary/replica model with consensus for writes, and versioned data (using MVCC - Multi-Version Concurrency Control) to provide snapshot isolation.
Key components:
Metadata Store: We need a distributed, consistent, and durable storage system. Options: etcd, Apache ZooKeeper, or a distributed SQL database like CockroachDB, TiDB, or even a distributed log like Apache Kafka with a compacted topic? But we need ACID transactions and snapshot isolation. So maybe a distributed SQL database that supports MVCC and is strongly consistent. Also, we need to handle high availability and multi-region replication.
Caching: Two layers: read cache (like Redis) and possibly a write cache? But writes should go through a coordination layer. Alternatively, we can have a service layer that caches reads.
Read/Write Paths:
Write: Clients send write requests to a primary (or a leader) that runs a consensus protocol (like Raft) to replicate and commit the change. The write must be durable and then acknowledged. The primary assigns a timestamp (or version) for the snapshot isolation.
Read: Clients can read from any replica (leader or follower) but must see a consistent snapshot. If reading from a follower, we need to ensure the follower is caught up to a snapshot that meets the read requirement (e.g., read at a specific timestamp). Also, we can cache reads in a distributed cache (like Redis) but need to invalidate or update on writes.
Multi-region Replication: We need to replicate data across regions. The metadata store should support multi-region deployment (like etcd with etcd clusters per region and a global consensus? Not straightforward). Alternatively, we can use a global distributed database that spans regions, but that may have latency issues. Another approach: have a primary in one region and read replicas in others. But if the primary region fails, we need failover. So we need a multi-primary or a way to elect a new primary. That's complex.
Repair Tooling: We need to detect and repair inconsistencies. This can be done by comparing checksums of data across replicas and fixing divergences. Also, we need to handle schema mismatches or partial failures.
High Availability: The system must be available even if some nodes or regions fail. We need quorum-based reads and writes.
Let's choose the storage engine: Apache Iceberg's catalog (like Nessie) uses a similar concept, but we're building from scratch. We can use an embedded key-value store with Raft? Or use an existing system.
But the question asks to "Build", so we need to design the architecture and specify the components.
We can outline:
Metadata Store: Use a distributed, strongly consistent database that supports MVCC and multi-region replication. For example, CockroachDB is a good choice because it's distributed SQL, supports MVCC, and has multi-region capabilities. Alternatively, we can use etcd but it's key-value only and not as scalable for large metadata? But metadata catalogs are usually not huge. etcd might work. However, etcd doesn't have multi-region replication out of the box (it's designed for a single cluster). There's etcd with etcd-operator for multi-region? Not typical. CockroachDB is designed for multi-region.
Given the requirement for snapshot isolation and multi-region, CockroachDB is a strong candidate. It uses MVCC, provides snapshot isolation (via SERIALIZABLE isolation level), and supports multi-region with survival goals.
But we also need repair tooling. CockroachDB has built-in repair? Not exactly. We might need to build some tools to check consistency across regions? Because CockroachDB replicates data using Raft per range, and it ensures consistency within a region? Actually, CockroachDB can be deployed in multiple regions with replication factors and localities. It handles replication and automatic failover. But what about cross-region network partitions? It uses consensus per range. So it's consistent.
However, the requirement says "repair tooling" which might imply we need to handle cases where the metadata store itself gets corrupted? Or maybe we need to repair the metadata from an external source (like the actual data lake)? The metadata catalog holds information about tables, partitions, locations, schemas, etc. The repair tooling might be used to rescan the data lake and correct the metadata if it diverges. That is separate from the storage engine's internal repair.
So we have two aspects:
Internal repair: the storage engine (CockroachDB) already handles replication and repair. But we might need to monitor and trigger repairs if a node is permanently down? That's operational.
External repair: our tool that scans the data lake and updates the catalog accordingly. That's more application-level.
We need to design the catalog service with the following:
API: REST or gRPC for clients to read and write metadata.
Service Layer: that interacts with the metadata store and caches.
Caching: Use a distributed cache (like Redis) for read-heavy operations. We need to invalidate or update the cache on writes.
Multi-region: Deploy the service in multiple regions with local read replicas of the metadata store and a global primary? Or if using CockroachDB multi-region, we can have the database handle replication. The service can be stateless and deployed in each region, and it connects to the nearest CockroachDB node (which is part of the global cluster). That gives low-latency reads.
But if the metadata store is CockroachDB, it already handles replication and multi-region. So we might not need separate read replicas; we can have all service instances connect to the same CockroachDB cluster deployed across regions. However, for low latency, we want reads to be served locally. CockroachDB supports "regional by row" or "regional by table" but not exactly local reads? Actually, CockroachDB can be configured with replica placement: we can set survival goals and localities such that each region has a replica. Then reads from a region can be served by the local replica (if we use "read from follower" with a timestamp that is not too recent). CockroachDB allows "staleful reads" by setting a timestamp in the past to read from a follower that is caught up. So we can have a service that, for reads, uses a timestamp that is a few seconds old to allow reading from any replica (including local followers). That gives low-latency reads. For writes, they must go to the leader, which may be in one region (but can be moved). That might cause higher write latency for remote regions. That's a trade-off.
Alternatively, we could have a primary per region? But then we need to synchronize across regions. That's more complex. Better to stick with a single global leader for writes? But if we want multi-region writes, we might need a multi-master setup. CockroachDB uses a single leader per range, but ranges are distributed. So writes can go to leaders in different regions depending on the data. But overall, the system uses a consensus protocol that requires majority across replicas. So if we have 3 regions with 1 replica each, a write must get majority (2). That means cross-region latency. So to have fast writes in each region, we would need to have a replica in that region be the leader for the relevant range. That's possible if we pin the leaseholder to a region? CockroachDB allows "lease preferences" to keep the leaseholder (which is the leader) in a particular region. So we could have lease preferences per region for different tables? But we want the metadata catalog to be globally consistent. So we might accept some latency for writes.
Given that metadata operations are not extremely frequent, we can tolerate some write latency.
So design:
Metadata Store: CockroachDB cluster deployed across regions with replication factor 3 (at least) and each region having at least one replica. We configure the cluster with "region" and "zone" information. We set survival goal to "region failure" meaning that if an entire region fails, we can still have a majority (if we have 3 regions, 2 remain). But we need to ensure that the leader can be elected in a remaining region. That's fine.
Service: We deploy a stateless service (maybe in Go or Java) that provides the catalog API. It connects to the CockroachDB cluster. It uses a connection pool to the database nodes. We can configure the service to use a load balancer that routes to the nearest CockroachDB node. But to get the best performance, we can have the service use a "smart driver" that knows the cluster topology and routes requests to the nearest replica that can serve it (like a follower for reads). But we might not need that; we can rely on CockroachDB's built-in load balancing.
But we also need a caching layer. We can put a Redis cluster in each region (or a global Redis cluster with replicas per region). But we need to ensure cache coherence. Since writes are not extremely frequent, we can use a write-through cache: writes update the database and then invalidate the relevant cache keys. Or we can use a time-to-live (TTL) for cache entries to avoid complex invalidation. But we need consistency: after a write, subsequent reads should see the update. If we use TTL, we might have stale reads for a while. That may be acceptable for some use cases, but for a metadata catalog, we usually want strong consistency? Actually, snapshot isolation provides a consistent view at a point in time. But if we use a cache, we might break isolation because the cache might return older data. So we need to decide: is it acceptable to have slightly stale metadata? Possibly, because data lake metadata is often used for planning queries; a few seconds of staleness might be okay. But some operations (like dropping a table) need immediate visibility to prevent writes to deleted tables. So we need to be careful.
We can have two types of reads: strong consistency (bypassing cache) and eventually consistent (using cache). The API could allow clients to specify consistency level? But that complicates.
Better: use cache for read-only operations that don't require immediate consistency (like list tables, get table details) but for operations that need latest data (like checking existence before write) we go to the database. But the catalog service itself uses the database for writes, and after a write, it invalidates the cache for that key. So read-after-write consistency is maintained because we invalidate. But if multiple services are writing, we need to coordinate cache invalidation. That can be done via a message bus? Or we can rely on the fact that all writes go through our service, and the service can invalidate the cache after committing the write. But if there are multiple instances of the service, each instance might have its own local cache? Better to have a distributed cache (like Redis) that all instances share. Then after a write, the service publishes an invalidation message to a channel (or directly deletes from Redis). That works.
But we also need to handle the case where a write fails after updating the database but before invalidating cache? Then cache is stale. We need to make the invalidation part of the same transaction? Not possible with separate Redis. So we need to be careful. We can use a cache that supports atomic operations, but still two-phase.
A common pattern: use a write-through cache where writes go to cache and then to database, and cache updates the database. But then we need to handle failures. Alternatively, use a cache that can be updated transactionally via a two-phase commit? Too heavy.
Simpler: after successful commit to database, we delete the key from Redis. But if the delete fails (e.g., Redis down), we have stale cache. That's a risk. We can also set a short TTL (like 5 seconds) so that even if invalidation fails, the stale data lives only a short time. Given that metadata changes are infrequent, that's acceptable.
So cache strategy: read-through: on cache miss, load from DB and set in Redis with TTL. Write: update DB, then delete from Redis (or update). Use TTL as a safety net.
Now, for multi-region replication of cache: we can have Redis replication across regions. But we need to ensure that invalidation is propagated. If we have a global Redis cluster (like Redis Cluster with nodes in multiple regions) it can replicate writes (including deletes) to all replicas. But that introduces latency. Alternatively, we can have a local Redis per region and use a pub/sub to propagate invalidations across regions. That's more complex.
Given that the metadata store is globally consistent, we could skip cache for cross-region and rely on the database's read replicas being local. Because CockroachDB can serve reads from local replicas if we use "staleful reads" (asymmetric). That might be simpler and avoid cache consistency issues. And metadata size might be manageable such that reading from the database is fast enough (milliseconds). So maybe we don't need a separate cache layer? But the requirement says "caching layers", so we should include.
But we could use CockroachDB's built-in block cache (in-memory) and also maybe an application-level cache. However, the requirement likely expects a separate caching layer.
Let's design with a distributed cache (Redis) per region, and we invalidate via delete after write. Also, we can use a "cache aside" pattern.
Now, snapshot isolation: CockroachDB provides snapshot isolation by default (using MVCC). When a client reads, it gets a snapshot at the transaction's start timestamp. So our service can simply start a transaction and read. That gives consistent view.
But if we use a cache, we break that because the cache is not versioned. So we need to be careful: we can cache the result of a read at a particular timestamp? That would be complex. So maybe we restrict cache to operations that don't require snapshot isolation? Or we don't use cache for transactions; we only use cache for simple GET operations that are read-only and we can tolerate staleness. Many catalog operations are simple gets (get table by name). So we can cache those with a short TTL. That's acceptable.
Now, repair tooling: We need a tool that can scan the data lake (the actual files in object storage) and compare with the catalog entries. It should detect missing or extra files, schema mismatches, etc. It can then either report or fix the catalog. This tool runs periodically or on demand.
We also need tooling for repairing the metadata store itself. If a region fails and we lose a replica, CockroachDB will automatically re-replicate. But if there is a split-brain or data divergence due to a bug, we might need manual intervention. CockroachDB has a repair command? Actually, it has cockroach debug merge and other tools. But we might need to build custom consistency checks between replicas? That's deep.
Maybe the repair tooling is focused on the metadata catalog vs the actual data. So we'll design an external consistency checker.
Now, let's outline the architecture:
Metadata Storage Layer:
CockroachDB cluster deployed across multiple regions (at least 3 regions) with each region having at least one node (VM/container). Replication factor 3 (so each piece of data is stored on 3 nodes, ideally in different regions). We configure the cluster with geographic localities and set the survival goal to "region failure". This ensures that if an entire region goes down, the cluster remains available (if we have at least 2 regions left with 3 replicas total). We also set the "primary region" for certain tables? Not needed.
Service Layer:
Deploy the catalog service (e.g., a Kubernetes Deployment) in each region. Each service instance is stateless and connects to the local CockroachDB node(s) via a load balancer. The service can use a connection pool.
The service exposes a REST/gRPC API for catalog operations: createDatabase, dropDatabase, createTable, alterTable, getTable, listTables, etc. It also provides an endpoint for the repair tool to interact.
The service implements caching: using a Redis cluster. Each region has its own Redis cluster (or a single Redis cluster with replicas across regions). Service instances in a region use the local Redis. Cache keys are based on the operation and parameters (e.g., "table:{id}"). TTL set to e.g., 10 seconds. On write, after committing to DB, we delete the relevant cache keys (or update). We also publish an invalidation event to a message bus (Kafka/PubSub) so that other regions' caches can be invalidated? If we have local Redis per region, we need cross-region invalidation. So we need a replication mechanism for cache invalidation. We could use Redis replication if we have a global master with read replicas in each region (but writes go to master, causing latency). Alternatively, we use a decentralized invalidation: each region's cache is independent, and we rely on TTL to eventually expire. But then after a write in Region A, a read in Region B might see stale data for up to TTL. That's maybe acceptable if TTL is short. But if we need strong consistency, we need cross-region invalidation. However, the database is strongly consistent and provides snapshot isolation; the cache is just an optimization. So we might decide that the cache is best-effort and not required for correctness. So we can accept stale reads for a few seconds. Then we don't need cross-region invalidation. But the requirement says "high-availability" and "snapshot isolation". If we read from cache, we may violate snapshot isolation because we might see an older version even if the transaction reads at a newer timestamp. So we should only use cache for non-transactional reads, or we need to version the cache. That's complex.
Maybe we avoid caching for operations that require snapshot isolation. The catalog service can have two modes: "consistent" (read from DB) and "cached" (read from cache with best-effort). The client can choose? Not ideal.
Another approach: the service uses a read-through cache that stores the result of a query at a specific timestamp. When reading, the service gets a timestamp from the database (current timestamp) and uses that to check the cache: if cache entry exists and its timestamp >= required timestamp? But that's not straightforward.
Now, let's produce a structured answer:
We'll describe:
System Overview
Components
Metadata Storage Layer
Service Layer
Caching Layer
Messaging Layer (for invalidation)
Repair Tool
Read/Write Paths
Multi-region Replication
Snapshot Isolation
High Availability & Fault Tolerance
Repair Tooling Details
Deployment Considerations
Potential Trade-offs and Limitations
We'll also include diagrams? Not needed in text, but we can describe.
Let's craft the response.
High‑Availability Metadata Catalog for Data Lakes
This design provides a globally available, strongly consistent metadata catalog with snapshot isolation, multi‑region replication, read/write paths optimized with caching, and automated repair tooling.
1. System Overview
The catalog stores metadata about databases, tables, partitions, schemas, and file locations in a distributed, ACID‑compliant store. Clients interact via a stateless service layer. Snapshot isolation is guaranteed by the underlying database. Caches accelerate read‑heavy workloads while a message bus ensures timely invalidation. The system spans multiple regions for resilience and low‑latency access. A separate repair tool periodically reconciles the catalog with the actual data lake.
2. Core Components
2.1 Metadata Storage Layer
Database: CockroachDB (distributed SQL with built‑in MVCC, serializable isolation, and multi‑region support).
Deployment: A cluster of nodes (≥3) distributed across ≥3 regions. Each region hosts at least one node.
Configuration:
Replication factor = 3, with constraints to spread replicas across regions.
Survival goal = region failure (cluster survives loss of an entire region).
Localities declared for each node (region=us-east1, zone=us-east1-a, etc.).
Guarantees: Strong consistency, automatic rebalancing, and online schema changes.
2.2 Service Layer
Technology: Stateless microservice (Go/Java) exposing REST and gRPC APIs.
Deployment: Kubernetes Deployment with replicas in each region behind a regional load balancer.
Responsibilities:
Translate client requests into transactions against CockroachDB.
Manage read‑through/write‑through caching.
Publish invalidation events.
Enforce authentication/authorization (e.g., via OAuth2/JWT).
Scalability: Horizontally scalable; any instance can handle any request.
2.3 Caching Layer
Technology: Redis Cluster (or Redis with Sentinel) deployed per region.
Cache Pattern: Cache‑aside (read‑through) with TTL (default 5 s) and explicit invalidation.
Consistency: Writes delete relevant keys immediately after committing to the DB; a short TTL bounds staleness even if invalidation fails.
2.4 Messaging Layer (Invalidation Bus)
Technology: Apache Kafka (or cloud‑native Pub/Sub) with replication across regions.
Use: After a successful write, the service publishes an Invalidate message containing the cache key(s). All service instances subscribe and delete those keys from their local Redis.
Durability: Messages are durably logged; consumers acknowledge only after successful cache deletion.
Scheduling: Can run on-demand or periodically (e.g., daily) as a batch job.
Safety: All fixes are optional and require explicit approval; a dry‑run mode is available.
3. Read & Write Paths
3.1 Write Path (with Invalidation)
code
Client → Load Balancer → Catalog Service Instance
1. Service starts a CockroachDB transaction (SERIALIZABLE).
2. Executes DML (INSERT/UPDATE/DELETE) on metadata tables.
3. Commits transaction → obtains commit timestamp.
4. Immediately after commit:
a. Publishes `Invalidate` messages to Kafka for affected keys.
b. Deletes those keys from the local Redis (synchronous best‑effort).
5. Returns success to client.
Note: Step 4 is performed after commit; if invalidation fails, the TTL will eventually evict stale entries.
3.2 Read Path (Cache‑First with Fallback)
code
Client → Load Balancer → Catalog Service Instance
1. Check Redis for the requested key.
2. If hit → return cached value.
3. If miss or expired:
a. Start a CockroachDB transaction with a fresh snapshot timestamp.
b. Read required metadata (ensuring snapshot isolation).
c. Store result in Redis with TTL.
d. Return result.
Consistency Note: Cached entries may be up to TTL seconds stale. For operations requiring the latest state (e.g., right after a write), the client can add a query parameter ?consistent=true; the service bypasses the cache and reads directly from the DB with a fresh snapshot.
4. Multi‑Region Replication
Metadata Store: CockroachDB replicates each range (shard) to 3 nodes in different regions. Raft consensus ensures consistency. A region failure reduces the replica quorum but the cluster survives (if ≥2 regions remain). Leaseholders (leaders) may shift to healthier regions automatically.
Service: Instances are deployed in every region. Clients are routed to the nearest region (via geo‑DNS or global load balancer), minimizing latency for both reads and writes. Writes that require a leader in a remote region incur cross‑region latency; however, CockroachDB’s lease preference can be tuned to keep leaders for frequently written ranges in a target region if needed.
Cache: Each region has its own Redis cluster. Invalidation messages are broadcast globally; all regions clear affected keys quickly (sub‑second propagation over Kafka).
Messaging: Kafka is configured as a multi‑region cluster with synchronous replication between clusters (e.g., MirrorMaker 2) to ensure invalidation events are visible everywhere.
5. Snapshot Isolation
CockroachDB implements MVCC and provides SERIALIZABLE isolation by default, which is stronger than snapshot isolation. The service relies on this for all database reads (when not using cache) and for all write transactions.
When the service reads from the database (bypassing cache), it explicitly uses a transaction with a single statement, which obtains a fresh snapshot timestamp guaranteeing a consistent view of the catalog at that instant.
6. High‑Availability & Fault Tolerance
Component
HA Mechanism
CockroachDB
Raft replication, automatic failover, online repair, and incremental backups.
Redis Cluster with replicas; failover via Redis Sentinel or automatic.
Kafka
Replicated logs across brokers; multi‑region mirroring.
Network/Region
Clients can fail over to another region if their primary region is down.
Data Durability
All writes are durably logged in CockroachDB and replicated across regions.
7. Repair Tooling – Detailed Design
The Catalog Repair Tool is a standalone application (or pipeline) that can be triggered manually or via a scheduler (e.g., Airflow, Kubernetes CronJob).
7.1 Execution Steps
Discovery:
List all objects in the data lake (using storage API with pagination).
For each file, optionally read footer (Parquet/Avro/ORC) to extract schema and partition values.
Catalog Snapshot:
Call GET /v1/catalog?consistent=true (or a dedicated bulk endpoint) to retrieve current catalog state.
This ensures the repair sees a consistent snapshot of the catalog.
Diff Analysis:
Compare storage vs. catalog:
Orphaned files: exist in storage but have no catalog entry.
Missing files: catalog entry points to a non‑existent object.
Schema drift: the schema derived from the file differs from the catalog schema (ignoring trivial differences like nullability).
Partition drift: partition values or locations do not match the file’s hive‑style partitioning.
If an --auto-fix flag is given, the tool calls the catalog service’s admin APIs (with elevated privileges) to apply changes in a transaction per affected object.
All changes are logged for auditability.
7.2 Scalability
The tool can run as a distributed job: split the keyspace (by database/table) across executors.
Storage listing can be parallelized using object storage’s prefix queries.
7.3 Safety
By default, the tool runs in dry‑run mode.
Fixes are idempotent and can be retried.
The tool can also validate that the catalog itself is internally consistent (e.g., no duplicate table names, valid foreign keys if any).
8. Deployment & Operational Considerations
Infrastructure: Use Kubernetes (or managed services: GKE, EKS, AKS) for the service and Redis CockroachDB can run on dedicated VMs or via its managed operator.
Observability: Export metrics (Prometheus), logs (structured), and traces (OpenTelemetry). Monitor:
DB latency, replication lag, node health.
Cache hit‑rate, evictions.
Kafka consumer lag.
Service error rates.
Backups: Daily full backups of CockroachDB to cloud object storage, plus point‑in‑time recovery via transaction logs.
Disaster Recovery: Simulate region failover regularly. Ensure the repair tool can recover from catalog inconsistencies after a major outage.
Security: TLS for all inter‑component communication, IAM roles for object storage access, network policies, and secret management.
9. Trade‑offs & Limitations
Cache Staleness: Even with immediate invalidation, a small window exists where a read may serve stale data from a different region’s cache before the invalidation arrives. TTL limits this to a few seconds. If strict linearizability is required, use the consistent=true flag.
Write Latency: Writes must go through CockroachDB’s consensus; cross‑region writes can incur latency (typically 50‑200 ms). If write latency becomes a bottleneck, consider leasing ranges to a specific region (but this may affect HA).
Complexity: Introducing Kafka, Redis, and CockroachDB increases operational overhead. Managed services can mitigate this.
Repair Tool Cost: Full data‑lake scans are expensive; schedule during off‑peak hours and use incremental scans (track last scanned token) where possible.
10. Summary
This architecture delivers a high‑availability, strongly consistent metadata catalog that can survive region failures, provides low‑latency reads via distributed caching, and includes automated tooling to keep the catalog faithful to the underlying data lake. By leveraging proven open‑source components (CockroachDB, Redis, Kafka) and a stateless service, the system scales horizontally and can be deployed across any cloud or on‑premises environment.
Build a high-availability metadata catalog for data lakes… · The Chat Archive
Given the complexity, maybe we skip the cache for now? But requirement says "caching layers". So we need to have some caching.
Let's think: The metadata catalog for data lakes often gets read heavily for listing tables and getting table schemas. Those operations can be cached. And they don't require linearizability; eventually consistent is fine. For example, if a table is created, it's okay if it appears in list a few seconds later. For writes, we need to ensure that concurrent writes are handled correctly via the database. So we can cache read-only operations that don't need immediate consistency.
We'll implement a cache for "get" and "list" operations with a short TTL and best-effort invalidation. On write, we publish an invalidation message to a global message bus (like Kafka) with the key to invalidate. All service instances subscribe and delete that key from their local cache (if they have a local cache). But we are using a shared Redis cluster, not local caches. So if we have one Redis per region, each region's Redis is independent. Invalidation via message bus: when a write occurs in region A, the service publishes an invalidation event to Kafka. Service instances in region B consume and delete from their local Redis. That ensures that within a short time, all caches are invalidated. The propagation delay is small (network latency). So we can achieve near-real-time invalidation. But if Kafka is down, invalidation might be delayed. We also have TTL as fallback.
That seems feasible.
Multi-region Replication for Metadata Store:
As said, CockroachDB handles it. We need to configure the cluster with regions and nodes such that each region has nodes, and we set the replication zone to have replicas in different regions. For example, we can set the replication factor to 3 and set constraints to have at least one replica in each of 3 regions, or use the "region" locality. Cobblestone.
Read/Write Paths:
Write:
Client sends a write request (e.g., createTable) to the catalog service. The service can route to any region (via load balancer). The service receives the request.
The service starts a transaction in CockroachDB with appropriate isolation (SERIALIZABLE). It executes the write (insert/update metadata tables).
Upon commit, the service then publishes an invalidation event to Kafka for the affected keys (e.g., table name, database list) and also deletes the keys from the local Redis (or sends delete to Redis).
Returns success to client.
Read (consistent):
For operations that require strong consistency (maybe the client can specify "consistent=true" or by default we use consistent reads?), the service bypasses the cache and reads from CockroachDB with a transaction that gets a consistent snapshot. That ensures snapshot isolation.
But we may want to use the cache for reads that can tolerate staleness. So we can have two endpoints: /v1/catalog (cached) and /v1/catalog?consistent=true (consistent). Or we can decide based on operation: GET /table/{id} can be cached; GET /table/{id}?consistent=strong bypasses cache. Another idea: the service always reads from the cache first, but if the cache entry is older than a threshold (e.g., 1 second), it goes to DB? That still might serve stale data if DB has updated but cache not invalidated yet. So not good.
Maybe we don't need to expose consistency level to clients. We can design the service to always read from the database for reads that are part of a write transaction? That's internal. For external reads, we can decide that all reads are eventually consistent and use cache with short TTL. But the requirement says "snapshot isolation". That implies that a read should see a consistent snapshot of the catalog as of a point in time. If we use a cache that might have partial updates or stale data, we violate that. So perhaps we must use the database for all reads to guarantee snapshot isolation. But the requirement also says "caching layers". So we need caching without violating isolation. This is tricky.
We can use the database's snapshot isolation and cache the entire result set? Not needed.
Another idea: we use a caching layer that sits between the service and the database but is consistent with the database's MVCC. Some databases support a consistent cache (like Oracle's result cache). CockroachDB does not have that.
Maybe we misinterpret: The requirement might be for a high-availability metadata catalog that itself uses snapshot isolation, and we are to design read/write paths, caching layers, etc. So we need to include caching to improve performance but not break isolation. One way is to use the cache for data that is not updated frequently, like table schemas, and we ensure that any update to that data invalidates the cache immediately. That gives strong consistency for that data because after invalidation, next read goes to DB and gets latest. But there is a window between write and invalidation where a read might get stale data from cache. That window is the time it takes to propagate invalidation. If we do invalidation synchronously after the write (i.e., before returning success), we can ensure that no read will see stale data after the write is acknowledged. However, reads that were already served from cache before the write might still be stale, but that's okay because they reflect the state before the write. The problem is: after the write, a read might hit a cache that hasn't been invalidated yet and return the old version. But if we do the invalidation synchronously as part of the write transaction (i.e., we delete the cache entry before committing? Not atomically). Actually, we can delete the cache entry after committing the transaction, but before returning success. The client will not see the write until after the write completes. But another client might read during that window? No, because the write hasn't returned yet, so the write is not yet visible? Wait: In MVCC, once the transaction commits, the new version is visible to subsequent transactions that start after the commit timestamp. If another client reads after the write commits but before invalidation, that read might go to the cache and get old data. That's a problem.
To avoid that, we need to ensure that any read that starts after the commit timestamp goes to the database, not the cache, until the cache is updated. We could use a mechanism where we mark the cache as invalid for that key for a brief period after a write. For example, after a write, we set a flag in a separate cache or we use a version number: each cache entry stores the version (commit timestamp) of the data. When reading, we compare the cached version with the latest version from the database (a cheap query to get the version). But that defeats the purpose of cache.
Another pattern: write-through cache where writes go to the cache and the cache updates the database. That ensures the cache always has the latest value. But then the cache becomes a single point of failure and must be highly available. And we need to handle concurrency. That's essentially making the cache the primary store, which is not what we want.
Perhaps we can use a cache that is only for data that is not updated frequently, and we rely on the fact that updates are rare and we use a long TTL but also trigger immediate invalidation across all caches. If invalidation is fast (sub-millisecond) and we do it before returning, then the window is very small and maybe we accept that risk? But still possible.
Alternatively, we can instrument the service to not use cache for any read that occurs after a recent write to that key. We could maintain a write log or a "dirty" set in memory (or in a separate shared store) that indicates which keys are recently written and need to bypass cache for a short time. That is complex in a distributed environment.
Given the complexity, maybe the requirement expects a design that uses a caching layer like Redis for read-heavy operations, and acknowledges that it may sacrifice strict snapshot isolation for performance, but we can mitigate by using short TTL and immediate invalidation via a message bus. Many large-scale systems do that. So we'll go with that.
We'll state: For read operations, the service first checks the cache. If present and not expired, returns cached value. If not, reads from the metadata store (CockroachDB) with snapshot isolation, and caches the result with a TTL (e.g., 5 seconds). On write, the service updates the metadata store and then publishes an invalidation message to a global message bus (Kafka) containing the keys affected. All service instances (and cache layers) subscribe and remove those keys from their local caches. This ensures that after a write, subsequent reads will fetch fresh data from the database within the propagation delay. The cache provides eventual consistency with a bounded staleness.
That's acceptable.
Repair Tooling:
We'll design a separate tool (or service) that can run periodically or on-demand.
It scans the data lake (object storage) for files and directories, and compares with the catalog's table and partition metadata.
It detects:
Catalog entries that point to missing files/locations.
Files in the data lake that are not registered in the catalog (orphaned files).
Schema mismatches: read the schema from the data files (e.g., Parquet footers) and compare with catalog schema.
Partition inconsistencies: check partition values and locations.
It can then generate a report or automatically fix the catalog (with user approval).
The tool runs as a distributed job (e.g., using Spark) because scanning the data lake could be huge.
It interacts with the catalog service via API (with consistent reads) to get catalog data, and uses object storage APIs to list files.
It can also be used to repair the metadata store itself: e.g., if a region is lost and some data is missing, we can restore from backup or from other replicas. But that's more about the database's own backup/restore. We'll assume the database handles that.
High Availability:
All components are deployed in multiple regions with redundancy.
CockroachDB: with at least 3 nodes across regions, automatic failover.
Service: multiple replicas behind a load balancer in each region.
Cache: Redis with replication and automatic failover (Redis Sentinel or Redis Cluster with replicas). In each region, we have at least a master and replica.
Message Bus: Kafka with replication across regions (using MirrorMaker or Confluent Multi-Region Cluster) to ensure durability.
Load balancers: per region.
Failure Modes:
Region failure: if a region goes down, traffic is routed to other regions. The CockroachDB cluster will continue with remaining replicas (if survival goal met). Service instances in other regions take over. Cache in that region is unavailable, but service will fall back to reading from DB (or use other region's cache? Not if local). If the region that fails had the primary for some ranges, a new leader will be elected in another region, causing a brief pause.
Network partition: The consensus protocol will ensure only one side can accept writes if a majority is available. This may cause writes to fail in minority partition. That's okay.
Backup and Restore: We need periodic backups of the metadata store (CockroachDB) to object storage. Also, we should have a way to restore.