Bird
Raised Fist0

Redis-Based Distributed Lock - Redlock Algorithm Design

HLDmediumInterview freq: medium
Choose your preparation mode4 modes available
▶
Request Trace
Step 1/7
Client Service

Sends lock request

Client initiates lock acquisition request to API Gateway

Protocol:WebSocket
BeforeClient has lock request ready to send
AfterLock request sent to API Gateway
API Gateway

Receives and forwards request

API Gateway receives request and forwards to Lock Manager

Protocol:HTTP/REST
BeforeAPI Gateway idle, waiting for requests
AfterLock request forwarded to Lock Manager
Lock Manager

Executes Redlock algorithm

Lock Manager sends SETNX commands with TTL to all 5 Redis nodes

Protocol:Redis SETNX with TTL
BeforeLock Manager has received lock request, no locks held
AfterLock Manager has acquired majority locks on Redis nodes
Redis Cluster (5 independent nodes)

Processes lock commands

Each Redis node attempts to set lock key with expiration atomically

Protocol:Redis SETNX with TTL
BeforeLock keys do not exist on Redis nodes
AfterLock keys set on majority of Redis nodes with TTL
Lock Manager

Validates lock acquisition

Lock Manager confirms majority success and returns lock token

Protocol:Internal method call
BeforeLock Manager awaiting Redis responses
AfterLock Manager confirms lock acquired, sends success to API Gateway
API Gateway

Responds to client

API Gateway sends lock acquisition success to Client Service

Protocol:WebSocket
BeforeAPI Gateway waiting for Lock Manager response
AfterClient Service receives lock acquisition success
Monitoring & Metrics

Records lock operation metrics

Collects timing and success/failure data for lock requests

Protocol:Internal metrics collection
BeforeNo metrics recorded for this lock request
AfterMetrics updated with lock acquisition data
🏗️
Architecture Diagram
Architecture Diagram
┌───────────────┐
│ Client Service│
└───────┬───────┘
        │ WebSocket
        ▼
┌───────────────┐
│  API Gateway  │
└───────┬───────┘
        │ HTTP/REST
        ▼
┌────────────────────────┐
│      Lock Manager       │
│ (implements Redlock)    │
└───────┬───────┬───────┬─┘
        │       │       │
        ▼       ▼       ▼
  ┌────────┐┌────────┐┌────────┐
  │ Redis  ││ Redis  ││ Redis  │
  │ Node 1 ││ Node 2 ││ Node 3 │
  └────────┘└────────┘└────────┘
      │        │        │
      ▼        ▼        ▼
  ┌────────┐
  │ Redis  │
  │ Node 4 │
  └────────┘
      │
      ▼
  ┌────────┐
  │ Redis  │
  │ Node 5 │
  └────────┘
      │
      ▼
┌───────────────────────┐
│ Monitoring & Metrics  │
└───────────────────────┘

The Redis-based distributed lock system uses the Redlock algorithm to ensure safe lock acquisition across five independent Redis nodes. The Client Service initiates a lock request via WebSocket to the API Gateway, which forwards it to the Lock Manager. The Lock Manager coordinates the Redlock algorithm by sending SETNX commands with TTL to all Redis nodes. Each Redis node attempts to set the lock key atomically. Once a majority of nodes confirm the lock, the Lock Manager returns success to the API Gateway, which notifies the client. Meanwhile, Monitoring & Metrics collects operational data for observability. This architecture ensures fault tolerance and safety by requiring a majority consensus among Redis nodes before granting the lock.

Primary Focus

✓

Practice

(1/5)
1. For the restaurant discovery feature, you must support millions of users searching by location with low latency. Which architecture is best suited given the constraint that restaurant data updates happen frequently (every few minutes)?
medium
A. Use a relational database with geospatial indexes and query directly for each user search
B. Use a distributed cache with geospatial indexing that asynchronously syncs updates from the primary database
C. Use a batch ETL pipeline to rebuild a search index every hour and serve queries from it
D. Use client-side filtering by downloading all restaurants in the city and filtering locally

Solution

  1. Step 1: Analyze read/write pattern for restaurant discovery

    High read volume with frequent writes requires low-latency reads and near-real-time updates.
  2. Step 2: Evaluate architectures

    Relational DB (A) can't handle query volume with low latency; batch ETL (C) is too stale; client filtering (D) is impractical for large data.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Distributed cache with async sync -> low latency + fresh data [check]
Hint: Async cache sync balances freshness and query speed [check]
Common Mistakes:
2. For ensuring exactly-once payment processing in a distributed payment system, which architecture is best suited given high throughput and fault tolerance requirements?
medium
A. Use an event-driven architecture with Kafka for event sourcing and idempotent consumers
B. Use a synchronous two-phase commit protocol across all services to guarantee atomicity
C. Use a centralized relational database with serializable transactions for all payment states
D. Use client-side retries with unique request IDs and eventual consistency in backend

Solution

  1. Step 1: Analyze architecture trade-offs

    Synchronous two-phase commit (Use a synchronous two-phase commit protocol across all services to guarantee atomicity) blocks and reduces throughput; centralized DB (Use a centralized relational database with serializable transactions for all payment states) limits scalability; client-side retries (Use client-side retries with unique request IDs and eventual consistency in backend) risk inconsistent states.
  2. Step 2: Evaluate event-driven approach

    Kafka event sourcing with idempotent consumers supports high throughput, fault tolerance, and exactly-once processing semantics.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Kafka event sourcing -> scalable, fault-tolerant, idempotent processing [check]
Hint: Event sourcing with idempotent consumers scales best [check]
Common Mistakes:
3. For internal service communication requiring bidirectional streaming with mobile clients that have intermittent connectivity, which approach is best?
medium
A. Use gRPC bidirectional streaming directly for real-time updates
B. Use gRPC unary calls with client-side polling and exponential backoff
C. Use WebSockets with JSON payloads for flexible streaming
D. Use REST long polling to simulate streaming behavior

Solution

  1. Step 1: Analyze client connectivity constraints

    Mobile clients often have intermittent connectivity and poor support for HTTP/2 streaming.
  2. Step 2: Evaluate streaming options

    Direct gRPC streaming (A) is unreliable on mobile. WebSockets (C) add complexity and JSON is less efficient. REST long polling (D) is less efficient and higher latency. Unary calls with polling and backoff (B) handle intermittent connectivity gracefully.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Mobile intermittent -> unary calls + polling with backoff [check]
Hint: Mobile clients -> unary calls + polling, not streaming [check]
Common Mistakes:
4. If the metrics aggregation service fails to update the error budget in real time, what is the most likely failure observed by the alerting system?
medium
A. Alerts trigger randomly due to inconsistent error count aggregation across nodes
B. Alerts never trigger because the error budget appears full and no burn rate is detected
C. Alerts trigger too frequently due to stale error budget values being reset to zero
D. Alerts show delayed notifications but eventually catch up after service recovery

Solution

  1. Step 1: Understand failure impact on error budget updates

    If aggregation service fails partially, inconsistent error counts across nodes cause alerting to behave erratically.
  2. Step 2: Eliminate other failure modes

    Resetting to zero (A) is unlikely without explicit reset; no alerts (B) implies total failure, not partial inconsistency; delayed alerts (D) imply buffering, not aggregation failure.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Aggregation failure -> inconsistent counts -> random alert triggers [check]
Hint: Aggregation failure causes inconsistent counts, leading to random alerts [OK]
Common Mistakes:
5. Without a distributed lock service, what exactly breaks when two instances concurrently update a shared configuration in a distributed system?
medium
A. Both updates succeed but the system crashes due to race conditions
B. One update overwrites the other silently, causing inconsistent configuration state
C. The system automatically queues updates and applies them sequentially
D. Updates are rejected by the database due to conflicting transactions

Solution

  1. Step 1: Understand lack of distributed locking

    Without distributed locks, concurrent updates can overwrite each other silently (B), causing inconsistent state.
  2. Step 2: Evaluate other options

    System does not automatically queue updates (C) without explicit coordination. Database rejecting conflicting transactions (D) depends on isolation level and may not prevent lost updates. System crash (A) is unrelated.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Concurrent updates without locks -> silent overwrite [check]
Hint: No lock -> silent overwrite, no automatic queuing [check]
Common Mistakes:
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard