The user wants a "high-availability metadata catalog for data lakes with snapshot isolation."
This is a complex system design problem. I need to break it down into its constituent components and address each requirement:
- Core Functionality: Metadata catalog (schema, partitioning, location, properties) for data lakes (e.g., S3, ADLS, GCS).
- High Availability (HA): No single point of failure, fault tolerance.
- Snapshot Isolation: Readers shouldn't block writers, writers shouldn't block readers. Atomicity and consistency.
- Read/Write Paths: How data flows in and out.
- Caching Layers: Performance optimization for high-throughput reads.
- Multi-Region Replication: Disaster recovery and latency reduction.
- Repair Tooling: Handling inconsistencies (data corruption, partial writes).
Architecture Decision - The "Metastore":
I shouldn't build a SQL database from scratch. I should leverage existing distributed consensus systems or databases, but design the application logic around them. However, to make this a "build" prompt, I will describe the architectural layers and implementation patterns.
Option A: Hive Metastore (RDBMS backed). Classic, but hard to scale HA and snapshot isolation efficiently without strict locking or MVCC tricks in the DB.
Option B: Iceberg/Delta Lake/Hudi style (File-based). These use the underlying file system (or a dedicated KV store) for metadata. They are inherently better for snapshot isolation.
Option C: Custom distributed KV store (e.g., DynamoDB/Cassandra) + Application Logic. This is often how modern catalogs (like Glue or internal ones at big tech) are built.
Let's go with a Hybrid Architecture:
- Storage Backend: A distributed, highly available Key-Value store (e.g., DynamoDB Global Tables or CockroachDB) for metadata pointers.
- Metadata Format: Apache Iceberg-like manifest files stored in object storage. This allows atomic updates via file swapping and provides snapshot isolation naturally.
Component Breakdown:
-
Data Model (The "Snapshot" aspect):
- A "Table" is a pointer to a metadata file.
- Commits involve: Write new data files -> Write new manifest file -> Swap pointer in Catalog.
- This ensures snapshot isolation. Old readers see the old pointer; new readers see the new one.
-
Write Path (Commit Protocol):
- Optimistic Concurrency Control (OCC).
- Client reads current version.
- Client writes changes to object store (immutable).
- Client tries to CAS (Compare-And-Swap) the pointer in the KV store.
- If fail, retry.
-
Read Path:
- Client reads pointer from Catalog.
- Client caches the manifest list.
- Client reads data files from Object Storage.
-
Caching:
- Client-side: Heavily cached (catalog pointer, manifest files).
- Server-side: Redis/Memcached for the KV store lookups (if KV latency is high, though DynamoDB is usually fast enough).
-
Multi-Region Replication:
- Active-Active: DynamoDB Global Tables or CRDT-based conflict resolution.
- Conflict Resolution: "Last Writer Wins" is dangerous for schema evolution. We need deterministic merging or vector clocks. Actually, for a catalog, distinct table IDs can be written anywhere, but updates to the same table across regions simultaneously is the edge case.
- Better approach: Designated primary region for specific table namespaces, or strictly serialized commits via a consensus layer (Paxos/Raft) across regions (high latency). Let's stick to a Global Database approach (like CockroachDB or Spanner) or DynamoDB Global Tables + application logic to handle the "split brain" on table pointers.
-
Repair Tooling:
- Consistency Checkers: Compare Catalog metadata vs. Physical files (Orphan files, Missing files).
- Rollback: Ability to revert pointer to previous snapshot ID.
Structuring the Response:
I will present this as a System Design Proposal.
- Title: "Chronos Lake Catalog" (just to give it a name).
- Core Architecture: File-based Metadata (Iceberg style) + Distributed KV Store.
- Detailed Sections:
- Data Model (Snapshot Isolation).
- Write Path (Optimistic locking).
- Read Path (Zero-copy reads).
- Caching Strategy.
- Multi-Region Strategy (Replication & Consistency).
- Repair & Maintenance.
Refining the details:
- Snapshot Isolation: Essential. I will describe the "Metadata Log" pattern. Instead of updating a single cell, we append to a log or swap a pointer.
- Multi-Region: This is the hardest part. If Region A writes v2 and Region B writes v2 simultaneously, how do we merge? For a catalog, usually, one region owns the write lease, or we accept eventual consistency with version vectors. I'll propose an "Active-Active with Version Vectors" approach.
Self-Correction during drafting:
Simply saying "use DynamoDB" is a bit lazy. I should explain how to model the data in it.
- Table ID -> Current Snapshot ID + Version Number.
- Snapshot ID -> List of Manifest Files (stored in S3).
Repair Tooling:
- Need a "Vacuum" process (delete old files).
- Need a "Consistency Audit" (scan S3, check against Catalog).
Code Examples:
I will provide pseudo-code or Go/Python snippets for the critical "Commit" logic to demonstrate the OCC pattern.
Let's build the outline:
- High-Level Architecture Diagram (Text description)
- Data Model:
Table points to Snapshot. Snapshot points to Manifests.
- The Write Path (OCC): Read-Modify-Write loop.
- The Read Path: Versioned reads.
- Caching: Multi-tier (Client -> Distributed Cache -> DB).
- Multi-Region: Async replication vs Sync Consensus. I'll choose Async Replication with Conflict Resolution logic for HA over Latency.
- Repair: CLI tools for fsck/vacuum.
Let's write the response. I will structure it as a technical design document.
This is a comprehensive design for "ChronoCatalog," a high-availability (HA), multi-region metadata catalog designed for data lakes (S3, ADLS, GCS).
This architecture borrows heavily from the patterns established by Apache Iceberg, Nessie, and Project Amundsen, focusing on separating the storage of metadata files from the transactional state of the catalog.
System Architecture: ChronoCatalog
1. High-Level Design
The catalog uses a Hybrid Architecture:
- Stateless API Layer: Handles authentication, validation, and logic.
- Transactional Database (The "Store"): Stores the current state of tables (pointers).
- Object Storage (The "Log"): Stores immutable snapshot files (manifest lists).
- Cache Layer: Reduces read latency for hot metadata.
2. Data Model & Snapshot Isolation
To achieve Snapshot Isolation (ACID), we treat table metadata as immutable. We never update a row in-place; we create a new version and update a pointer.
The Core Entities
- Table Object: Stores the current
snapshot_id and location.
- Snapshot Record: An immutable file (stored in S3/GCS) containing the list of data files (manifests) for that specific version.
The Isolation Protocol (Optimistic Concurrency Control)
When a client writes data, they do not lock the table. They perform a Compare-And-Swap (CAS) operation:
- Read: Client reads
current_snapshot_id = 101.
- Write: Client writes new data files to the data lake.
- Commit: Client sends a request to the API: "Create a new snapshot 102 derived from 101."
- Validation: The database transaction ensures the current pointer is still
101.
- Success: Update pointer to
102.
- Fail (Conflict): Another writer moved the pointer to
102 already. The client must pull 102, reconcile changes, and retry.
3. Write Path (The Commit Workflow)
This path prioritizes durability and consistency over raw latency.
sequenceDiagram
participant Writer (Spark/Flink)
participant API Gateway
participant Catalog DB (DynamoDB/Spanner)
participant Object Store (S3)
Writer->>API Gateway: CommitTransaction(base_snapshot=101, new_files=[...])
API Gateway->>Object Store: 1. Write Manifest List (immutable)
Note right of API Gateway: This write is cheap and safe. If it fails, txn aborts.
Object Store-->>API Gateway: Location: s3://meta/snap-102.avro
API Gateway->>Catalog DB: 2. Conditional Update
Note right of Catalog DB: SET current_snap=102 WHERE current_snap=101
alt Success
Catalog DB-->>API Gateway: OK
API Gateway-->>Writer: 200 OK
else Conflict (Snap is 105)
Catalog DB-->>API Gateway: ConditionalCheckFailed
API Gateway->>Object Store: Cleanup s3://meta/snap-102.avro (Async)
API Gateway-->>Writer: 409 Conflict (Retry)
end
Tech Stack Choice:
- Database: AWS DynamoDB (Global Tables) or Google Spanner. Both offer atomic
Compare-And-Swap operations natively.
- Logic: The API layer is stateless Go/Rust code.
4. Read Path & Caching Layers
Reads occur much more frequently than writes. We need a multi-tiered caching strategy to prevent thundering herds on the database.
Layer 1: Client-Side Caching (In-Memory)
Compute engines (Spark, Trino, Flink) maintain a local LRU cache of table metadata.
- TTL: 5 seconds (configurable).
- Pros: Zero network overhead for repeated reads.
Layer 2: Distributed Cache (Redis Cluster)
If the client cache misses, it hits the Redis cluster.
- Key Structure:
catalog:database:table:snapshot_id
- Pros: Handles high concurrency.
- Invalidation: We use a Write-Through strategy. When the API successfully commits a new snapshot to the DB, it immediately updates Redis.
Layer 3: The Database (Source of Truth)
If Redis misses, we fetch from the Catalog DB.
- We fetch only the lightweight pointer (Snapshot ID).
- We then fetch the heavy Manifest List from the Object Store (S3) directly to the client to save bandwidth on the Catalog API.
5. Multi-Region Replication (Active-Active)
To support global data lakes, the catalog must survive region failure.
Strategy A: Strong Consistency (The "Cloud Native" Way)
- Database: Use Google Cloud Spanner or AWS DynamoDB Global Tables.
- Mechanism: These systems handle the replication of the primary key (Table ID -> Snapshot ID) synchronously or semi-synchronously.
- Conflict Resolution: Last-Writer-Wins (LWW) based on atomic clocks (TrueTime in Spanner).
- Note: This effectively serializes global writes. If two people write to the same table in EU and US simultaneously, one will fail the CAS check.
Strategy B: Storage Layer Replication
The metadata files (Manifest Lists) written to S3 must be accessible globally.
- Use CRR (Cross-Region Replication) for the metadata bucket.
- Readers in Region B read from the local replica bucket; the Catalog DB points to the generic URI (
s3://...) which resolves to the local copy via Edge logic or simply allows cross-region GETs.
6. Repair & Maintenance Tooling
Metadata drift is inevitable. Files get deleted outside the catalog, or writes fail halfway.
Tool A: The "Vacuum" (Orphan File Cleaner)
- Function: Scans the Object Store for files that are not referenced by any active snapshot in the Catalog DB.
- Safety: Only deletes files older than a threshold (e.g., 7 days) to ensure no in-flight transactions are using them.
Tool B: Consistency Checker (The "Scraper")
A background service that runs every hour:
- List all snapshots in the Catalog DB.
- Verify that the metadata file exists in S3.
- Action: If missing, mark the snapshot as "Corrupted" and alert admins. If the current snapshot is missing, trigger an automatic rollback to the previous valid snapshot.
Tool C: Reverse Indexer
- Function: Rebuilds the catalog index if the DB is lost.
- Logic: Scans the Object Store bucket for known file naming patterns (e.g.,
snap-...avro) and attempts to reconstruct the table history by reading the headers of these files.
7. Implementation Skeleton (Pseudo-Code)
Here is the core logic for the Commit function in the Catalog API.
package main
import (
"errors"
"fmt"
"time"
)
// Represents the lightweight entry in our distributed DB
type TableEntry struct {
TableName string
CurrentSnapID int64
CurrentSnapURI string
LastUpdated time.Time
}
// CatalogInterface abstracts the DB (DynamoDB/Spanner)
type CatalogInterface interface {
GetTable(name string) (TableEntry, error)
CompareAndSwap(name string, oldSnapID int64, newSnapID int64, newSnapURI string) error
}
func CommitTransaction(client Client, catalog CatalogInterface, req CommitRequest) error {
// 1. Get current state
currentEntry, err := catalog.GetTable(req.TableName)
if err != nil {
return err
}
// 2. Optimistic Lock Check
if currentEntry.CurrentSnapID != req.BaseSnapID {
return errors.New("conflict: table has been modified by another process")
}
// 3. Create new metadata file (Immutable)
// We write the list of new files to S3/GCS first.
// If this fails, the transaction fails safely.
newSnapURI, err := client.WriteManifest(req.NewFiles)
if err != nil {
return fmt.Errorf("storage write failed: %v", err)
}
// 4. Generate new ID (Monotonic or UUID)
newSnapID := time.Now().UnixNano()
// 5. Commit to Database (Atomic CAS)
// This effectively creates the "Snapshot Isolation"
err = catalog.CompareAndSwap(
req.TableName,
currentEntry.CurrentSnapID, // Expected Old Value
newSnapID, // New Value
newSnapURI, // New Pointer
)
if err != nil {
// 6. Cleanup orphaned manifest file we just wrote
// because the DB transaction failed.
go client.DeleteObject(newSnapURI)
return fmt.Errorf("transaction aborted (concurrent modification): %v", err)
}
return nil
}
Summary of Availability Features
- Fault Tolerance: Stateless API allows horizontal scaling; DB replication handles data persistence.
- Isolation: Optimistic Concurrency Control (CAS) ensures readers never see partial writes.
- Performance: Separation of "Pointer" (DB) and "Payload" (S3) ensures the DB is never bottlenecked by large schemas.
- Recovery: The immutable nature of snapshots allows instant rollback (simply update the pointer to an old ID).