Design a Kubernetes-Based Object Metadata Store with Cassandra
System DesignModel answerLast updated
Design an API metadata service on Kubernetes and Cassandra featuring exact-once unique name constraints, soft-delete state transitions, and high-performance read strategies.
You are tasked with designing a stateless Java web application running on Kubernetes that interfaces with an Apache Cassandra cluster. The service acts as an artifact metadata management system where each artifact is identified by a unique, user-defined string key (the artifact name).
Your system design must explicitly address the following three dimensions:
-
Concurrency & Uniqueness on Ingestion (
Create):- Explain how you guarantee that an artifact name is created exactly once, even under extreme concurrent requests and client retries.
- Detail the primary key schema, idempotency keys, write consistency levels, concurrency mechanisms (e.g., Lightweight Transactions / Paxos vs. external locking), error handling (e.g., CAS timeouts), and failure modes.
-
Deletion & Lifecycle Management (
Delete& Re-creation):- Formulate a strategy for handling deletions and potential re-creations of previously used artifact names.
- Address anti-entropy challenges like Cassandra tombstones, data resurrection/zombies, tombstone compaction, generation tracking, and soft-delete state transitions.
-
Read Optimization & Resiliency (
Get&List):- Architect the read path to support low-latency metadata retrieval under high traffic volumes.
- Describe your read consistency choices (
LOCAL_QUORUMvsLOCAL_ONE), multi-layer caching, pagination over partition key distributions, mitigation of hot partitions, and fallback mechanisms during partial node or network outages.
Hints
Hint 1
Consider separating binary file storage (S3/GCS) from metadata storage (Cassandra) to avoid small-sstable performance bottlenecks.
Hint 2
Cassandra LWTs (Lightweight Transactions) use Paxos internally; understand how Paxos handles network timeouts on write acknowledged steps versus unacknowledged state transitions.
Hint 3
Using standard SQL/CQL hard DELETE statements in Cassandra writes tombstones, which can cause read performance degradation and data resurrection if gc_grace_seconds expires before repair runs.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Architectural Overview & Core System Boundaries
An end-to-end artifact metadata service must separate binary storage from structural metadata. Cassandra is optimized for fast, predictable structured writes across distributed nodes, but performs poorly with large BLOB payloads.
┌─────────────────────────────────────────┐
│ Kubernetes Ingress │
└────────────────────┬────────────────────┘
│
┌─────────────────┴─────────────────┐
│ Java Web Services (Stateless API)│
└──────┬──────────────────────┬─────┘
│ (Metadata) │ (Payload Presigned URL)
▼ ▼
┌──────────────────┐ ┌──────────────────┐
│ Apache Cassandra │ │ Object Storage │
│ Metadata DB │ │ (S3 / MinIO) │
└──────────────────┘ └──────────────────┘
Assumptions & Operational Constraints
- Traffic: 2,000 writes/sec (peak), 50,000 reads/sec (read-heavy, ~25:1 read-to-write ratio).
- Latency Budget: Metadata
GETrequests sub-15ms p99;POSTcreations sub-50ms p99. - Topology: Stateless Java API deployed via Deployment resources with Horizontal Pod Autoscaler (HPA). Cassandra running as a multi-zone cluster across 3 Availability Zones (AZs) with Replication Factor
RF = 3usingNetworkTopologyStrategy.
1. Concurrency Control and Unique-Name Creation
To guarantee that an artifact name is created exactly once, we must eliminate check-then-act race conditions across stateless API pods.
Primary Schema Design
CREATE TABLE artifact_metadata (
artifact_name text,
generation bigint,
artifact_id timeuuid,
owner_id text,
lifecycle_state text, -- 'ACTIVE', 'DELETED'
idempotency_key text,
payload_uri text,
created_at timestamp,
deleted_at timestamp,
PRIMARY KEY (artifact_name)
);
Because artifact_name is the sole partition key, all operations concerning a specific name hash to the same Cassandra token range and are coordinated by the exact same replica set acting as Paxos acceptors.
Concurrency Engine: Lightweight Transactions (LWT)
We use Cassandra's native Paxos implementation (Lightweight Transactions) instead of external locking systems like Redis Redlock or ZooKeeper. External locks introduce distributed state sync issues, lease expiration risks during Java JVM Stop-the-World GC pauses, and require fencing tokens.
Atomic Creation Query
INSERT INTO artifact_metadata (
artifact_name, generation, artifact_id, owner_id,
lifecycle_state, idempotency_key, payload_uri, created_at
)
VALUES (?, 1, ?, ?, 'ACTIVE', ?, ?, toTimestamp(now()))
IF NOT EXISTS;
- Serial Consistency:
LOCAL_SERIAL(executes Paxos phase 1 and 2 within the local datacenter). - Write Consistency:
LOCAL_QUORUM(commits state change to a quorum of replicas).
Execution Algorithm & Idempotency Resolution
[ Client Request ]
│ (Header: Idempotency-Key)
▼
1. Stage binary payload to Object Store under unique UUID path
│
▼
2. Execute Cassandra LWT: `INSERT ... IF NOT EXISTS`
│
├─────────────────────────────────┐
[ Paxos Succeeded: [applied] = true ] [ Paxos Failed: [applied] = false ]
│ │
▼ ▼
Return HTTP 201 Created 3. Read existing row state
│
├───────────────────────────────┐
[ Same Idempotency Key ] [ Different Idempotency Key ]
│ │
▼ ▼
Return HTTP 200 OK Return HTTP 409 Conflict
(Replay payload metadata) (Name already claimed)
Failure Mode: Handling WriteTimeoutException on LWT
When an LWT times out with a WriteTimeoutException (specifically when WriteType.CAS is returned), the client cannot know whether the Paxos round committed.
Resolution Protocol:
- Do not return a 500 error or assume failure.
- Immediately issue a
LOCAL_SERIALread for theartifact_name. ALOCAL_SERIALread forces a Paxos round completion if a commit was in-flight, evaluating the authoritative state. - If the read returns an
ACTIVErow:- If the recorded
idempotency_keymatches the request, returnHTTP 201 Created(or200 OK). - If the recorded
idempotency_keydiffers, returnHTTP 409 Conflict.
- If the recorded
- If the read times out again, abort and return
HTTP 503 Service Unavailablewith aRetry-Afterheader. The client safely retries using the exact sameIdempotency-Key.
2. Lifecycle Management: Deletes, Re-adds, and Anti-Entropy
Executing standard DELETE statements in Cassandra writes tombstones. Excessive tombstones degrade read latencies (scanning deleted cells) and risk data resurrection (zombies) if a node remains down past gc_grace_seconds and misses a tombstone before compaction purges it.
Soft-Delete State Machine via LWT
We treat deletions and re-creations as explicit state transitions guarded by monotonic generation sequence numbers rather than physical deletes.
┌─────────────────────────┐
│ Non-existent │
└────────────┬────────────┘
│
LWT: IF NOT EXISTS
│
▼
┌─────────────────────────┐
┌──────>│ ACTIVE │
│ └────────────┬────────────┘
│ │
LWT: IF state='DELETED' │ LWT: IF state='ACTIVE'
AND gen = current_gen │ AND gen = current_gen
│ │
│ ▼
│ ┌─────────────────────────┐
└───────┤ DELETED │
└─────────────────────────┘
Deletion Statement
UPDATE artifact_metadata
SET lifecycle_state = 'DELETED',
deleted_at = toTimestamp(now())
WHERE artifact_name = ?
IF lifecycle_state = 'ACTIVE' AND generation = ?;
If a client attempts to delete an artifact with a stale generation, the condition returns [applied] = false, preventing race conditions where an old delete wipes out a newly re-created incarnation of the name.
Re-creation (Reuse of Name) Statement
If a client issues a POST for a name that currently exists in state 'DELETED', the application attempts a transition update:
UPDATE artifact_metadata
SET lifecycle_state = 'ACTIVE',
generation = ? + 1,
artifact_id = ?,
owner_id = ?,
idempotency_key = ?,
payload_uri = ?,
created_at = toTimestamp(now()),
deleted_at = null
WHERE artifact_name = ?
IF lifecycle_state = 'DELETED' AND generation = ?;
Asynchronous Cleanup & Tombstone Mitigation
- Blob Garbage Collection: When a row transitions to
DELETED, an asynchronous worker places(artifact_id, payload_uri)onto a delayed message queue (e.g., Kafka or SQS with a 24-hour delay window). The worker eventually purges the underlying binary object from Object Storage. - Cool-down Period: Name reuse is configured with a safety window (e.g., 60 seconds post-deletion) to allow downstream cache invalidation to propagate.
- Compaction Strategy: For tables with high-churn key spaces, use
LeveledCompactionStrategy(LCS) to contain deleted rows within smaller SSTable overlaps, reducing read latency penalties if physical deletes are ever executed by background maintenance jobs.
3. Read Path Architecture, Latency Optimization, and Resilience
Read operations must scale to 50,000 req/sec while guaranteeing minimal tail latency.
┌──────────────────────────────────┐
│ Client GET │
└────────────────┬─────────────────┘
│
▼
┌──────────────────────────────────┐
│ Application Local L1 Cache │
│ (Caffeine) │
└────────────────┬─────────────────┘
│ Miss
▼
┌──────────────────────────────────┐
│ Distributed L2 Cache Cluster │
│ (Redis) │
└────────────────┬─────────────────┘
│ Miss
▼
┌──────────────────────────────────┐
│ Cassandra Metadata Cluster │
│ Consistency Level: LOCAL_QUORUM
└──────────────────────────────────┘
Read Consistency & Tuning Strategies
- Primary Single-Key Lookup (
GetArtifact): Executed usingConsistencyLevel.LOCAL_QUORUMto prevent reading stale metadata following an update. - Cache Architecture:
- L1 (In-Memory): Caffeine cache local to each Java API pod (TTL: 2 seconds) to absorb high-frequency micro-bursts on identical keys.
- L2 (Distributed): Redis cluster storing serialized metadata (TTL: 1 hour). Invalidated on state updates/deletions.
- Speculative Execution: Configure the DataStax Java Driver's
SpeculativeExecutionPolicy. If a replica fails to answer a read query within the p99 threshold (e.g., 8ms), the driver automatically dispatches a parallel request to a third replica node, neutralizing tail-latency spikes caused by background JVM garbage collection on Cassandra nodes.
Paginated Queries over Large Datasets
For owner-based queries (GET /artifacts?owner_id=X), storing all records under a single partition key (owner_id) creates hot partitions when single owners hold millions of artifacts.
Bucketed Owner Index Schema
CREATE TABLE artifacts_by_owner (
owner_id text,
bucket int, -- Hash-based bucket: (hash(artifact_name) % 10)
created_at timestamp,
artifact_name text,
artifact_id timeuuid,
lifecycle_state text,
PRIMARY KEY ((owner_id, bucket), created_at, artifact_name)
) WITH CLUSTERING ORDER BY (created_at DESC, artifact_name ASC);
- Query Pattern: To fetch an owner's artifacts, the API queries across all fixed buckets ($B_0 \dots B_9$) in parallel using Cassandra native driver
PagingStatelimits, merging the streams in memory at the Java API layer. - Hot Partition Defense: Hashing the
artifact_nameinto discrete partition buckets distributes an individual user's data uniformly across distinct physical Cassandra nodes.
Partial Outage Fallback Protocol
┌────────────────────────┐
│ Primary LOCAL_QUORUM │
└───────────┬────────────┘
│ Fail / Timeout
▼
┌────────────────────────┐
│ Read Fallback (L2/L1) │
└───────────┬────────────┘
│ Stale Cache Miss
▼
┌────────────────────────┐
│ Downgrade Consistency: │
│ LOCAL_ONE │
└───────────┬────────────┘
│
▼
Return Payload with Header:
`X-Degraded-Read: true`
- Local Quorum Degradation: If
LOCAL_QUORUMfails due to multiple Cassandra node outages within an Availability Zone:- Read path falls back to serving unverified data from Redis L2 cache if present.
- If L2 misses, degrade read consistency dynamically to
LOCAL_ONE. - Set an HTTP response header
X-Degraded-Read: trueto inform the caller that linearizability guarantees are temporarily relaxed.
- Write Degradation: LWT operations require a quorum for Paxos steps. If quorum is lost, mutations MUST fail fast with
HTTP 503to prevent split-brain state mutations. Writes must never degrade below quorum consistency.
4. Summary Matrix of Concurrency & Operations
| Scenario | Mechanism | Consistency Level | Edge Case / Risk | Mitigation |
|---|---|---|---|---|
| New Create | INSERT ... IF NOT EXISTS | LOCAL_SERIAL | Network timeout during Paxos commit | Perform immediate serial read check; resolve idempotency key |
| Re-creation | UPDATE ... IF state='DELETED' | LOCAL_SERIAL | Race with late-arriving delete | State sequence check (generation = gen + 1) aborts stale operations |
| Delete | UPDATE SET state='DELETED' | LOCAL_SERIAL | Tombstone accumulation & Zombie resurrection | Use soft deletes; manage payload purge via delayed queues |
| High Read Vol | Multilevel Cache + Speculative Read | LOCAL_QUORUM | Cassandra node GC pause causing p99 spikes | Drive parallel speculative queries after 8ms deadline |