Design a Fault-Tolerant Redis Wrapper with Exponential Backoff and a Circuit Breaker
Quick Overview
Design a wrapper over several Redis-like key-value instances that routes keys with a deterministic hash, retries failed operations with exponential backoff, and opens a per-instance circuit breaker after repeated failures. It tests careful state handling, retry and delay counting, and exact return values on every path.
Design a Fault-Tolerant Redis Wrapper with Exponential Backoff and a Circuit Breaker
Company: Tesla
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design a service class that simulates CRUD operations across a set of Redis-like key-value store instances. The system must implement a retry mechanism with exponential backoff and a circuit breaker pattern to handle instance failures gracefully.
Each instance is identified by a 0-based index. Instances can be marked as down or brought back up. Keys are distributed to instances using a deterministic hash: `instance_index = sum(ord(c) for c in key) % numInstances`.
The class is constructed as `FaultTolerantRedis(numInstances: int, maxRetries: int, baseDelay: int, failureThreshold: int)`. Every instance starts up, with an empty store and a closed circuit.
When an operation fails, it retries up to `maxRetries` times, so one call makes at most `maxRetries + 1` attempts. The first attempt has no delay, and the backoff delay doubles each retry starting from `baseDelay` (the delays are `baseDelay`, `2 * baseDelay`, `4 * baseDelay`, ...). In this simulation, delays are tracked but not actually waited: each call reports the total delay it accumulated.
Each instance has its own circuit breaker. After `failureThreshold` consecutive failures on an instance, the circuit opens and all subsequent requests to that instance fail immediately (without attempting the operation) until the circuit is manually reset. When the circuit is open, attempts still count toward retry logic but do not increment the failure counter. A successful attempt resets that instance's failure counter to 0. Marking an instance up does not close its circuit; only `resetCircuit` does.
A call that fails on every attempt reports `'CIRCUIT_OPEN'` if the instance's circuit is open after its last attempt (including when it opened during this call), and `'INSTANCE_DOWN'` otherwise.
Implement the following methods:
- `set(key: str, value: str) -> list`: Set a key-value pair on the appropriate instance. Returns `[success (0/1), message, totalDelay]`. Message is `'OK'` on success, `'INSTANCE_DOWN'` or `'CIRCUIT_OPEN'` on failure.
- `get(key: str) -> list`: Get the value for a key from the appropriate instance. Returns `[success (0/1), value or 'NULL' or error message, totalDelay]`.
- `delete(key: str) -> list`: Delete a key from the appropriate instance. Returns `[success (0/1), 'OK'/'NOT_FOUND' or error message, totalDelay]`.
- `markDown(instanceIndex: int) -> str`: Mark an instance as down (simulates failure). Returns `'OK'` or `'INVALID_INDEX'`.
- `markUp(instanceIndex: int) -> str`: Mark an instance as up (simulates recovery). Returns `'OK'` or `'INVALID_INDEX'`.
- `resetCircuit(instanceIndex: int) -> str`: Reset the circuit breaker for an instance, closing it and clearing the failure count. Returns `'OK'` or `'INVALID_INDEX'`.
- `getInstanceIndex(key: str) -> int`: Return the instance index that a given key maps to (sum of ASCII values mod `numInstances`).
- `isCircuitOpen(instanceIndex: int) -> int`: Return 1 if the circuit breaker for the given instance is open, 0 if closed, -1 if the index is invalid.
Example 1:
```text
r = FaultTolerantRedis(2, 2, 100, 3)
r.getInstanceIndex("b") # 0 (98 % 2)
r.getInstanceIndex("ab") # 1 (97 + 98 = 195, 195 % 2)
r.set("ab", "x1") # [1, "OK", 0]
r.get("ab") # [1, "x1", 0]
r.get("b") # [1, "NULL", 0]
r.delete("ab") # [1, "OK", 0]
r.delete("ab") # [1, "NOT_FOUND", 0]
r.markDown(2) # "INVALID_INDEX"
r.isCircuitOpen(2) # -1
```
All instances are healthy, so every data call succeeds on its first attempt with a delay of 0. A missing key is still a successful call: `get` returns `'NULL'` and `delete` returns `'NOT_FOUND'`. With two instances, index 2 is out of range.
Example 2:
```text
r = FaultTolerantRedis(2, 2, 100, 4)
r.set("b", "v1") # [1, "OK", 0]
r.markDown(0) # "OK"
r.set("a", "w2") # [1, "OK", 0]
r.get("b") # [0, "INSTANCE_DOWN", 300]
r.isCircuitOpen(0) # 0
r.get("b") # [0, "CIRCUIT_OPEN", 300]
r.isCircuitOpen(0) # 1
r.markUp(0) # "OK"
r.get("b") # [0, "CIRCUIT_OPEN", 300]
r.resetCircuit(0) # "OK"
r.get("b") # [1, "v1", 0]
```
Key `"b"` maps to instance 0 and key `"a"` to instance 1, so the outage on instance 0 does not affect `"a"`. The first failing `get("b")` makes three attempts on a down instance: the failure counter reaches 3, below the threshold of 4, and the delay is 100 + 200 = 300. The next call's first attempt brings the counter to 4 and opens the circuit, its two retries fail fast, and it reports `'CIRCUIT_OPEN'` with the same 300 delay. Marking the instance up leaves the circuit open, and after `resetCircuit` the value stored before the outage is readable again.
```hint Count attempts and delays
Write out every attempt for `maxRetries = 2` and mark which ones add a delay and how much. Mixing up retries and attempts is the easiest way to get the totals wrong.
```
```hint Order the checks
An attempt can fail because the circuit is open or because the instance is down. Decide which one you test first and check that choice against the rule that an open circuit does not add to the failure count. Also decide exactly when the failure count goes back to zero.
```
### Constraints & Assumptions
- `1 <= numInstances <= 10`
- `0 <= maxRetries <= 5`
- `1 <= baseDelay <= 1000`
- `1 <= failureThreshold <= 10`
- Keys are non-empty strings of lowercase English letters.
- Values are non-empty strings of lowercase English letters and digits.
- At most `1000` operations will be performed.
- An instance that is marked down keeps its data. Once it is up and its circuit is closed, keys written earlier are readable again.
### What a Strong Answer Covers
- How state is split across instances, and why a failing instance cannot affect keys that hash to another one.
- The retry loop: how many attempts a call makes, which attempts add a delay, and the total delay of a call that fails on every attempt.
- The order of checks inside one attempt, and exactly when the failure counter rises, resets, or opens the circuit.
- The return value on every path, including missing keys, invalid indices and a circuit that opens partway through a call.
- Per-call time complexity, and how this simulated breaker differs from one a production client would use.
### Follow-up Questions
- How would you add a half-open state so the circuit closes on its own after a cool-down?
- How would you add jitter to the backoff, and what problem does it solve when many clients fail at once?
- If an instance could fail after applying a write but before replying, which of these operations are still safe to retry?
- How would you make the wrapper safe to call from many threads at once?
Overview: Design a wrapper over several Redis-like key-value instances that routes keys with a deterministic hash, retries failed operations with exponential backoff, and opens a per-instance circuit breaker after repeated failures. It tests careful state handling, retry and delay counting, and exact return values on every path.
Design a service class that simulates CRUD operations across a set of Redis-like key-value store instances. The system must implement a retry mechanism with exponential backoff and a circuit breaker pattern to handle instance failures gracefully.
Each instance is identified by a 0-based index. Instances can be marked as down or brought back up. Keys are distributed to instances using a deterministic hash: instance_index = sum(ord(c) for c in key) % numInstances.
The class is constructed as FaultTolerantRedis(numInstances: int, maxRetries: int, baseDelay: int, failureThreshold: int). Every instance starts up, with an empty store and a closed circuit.
When an operation fails, it retries up to maxRetries times, so one call makes at most maxRetries + 1 attempts. The first attempt has no delay, and the backoff delay doubles each retry starting from baseDelay (the delays are baseDelay, 2 * baseDelay, 4 * baseDelay, ...). In this simulation, delays are tracked but not actually waited: each call reports the total delay it accumulated.
Each instance has its own circuit breaker. After failureThreshold consecutive failures on an instance, the circuit opens and all subsequent requests to that instance fail immediately (without attempting the operation) until the circuit is manually reset. When the circuit is open, attempts still count toward retry logic but do not increment the failure counter. A successful attempt resets that instance's failure counter to 0. Marking an instance up does not close its circuit; only resetCircuit does.
A call that fails on every attempt reports 'CIRCUIT_OPEN' if the instance's circuit is open after its last attempt (including when it opened during this call), and 'INSTANCE_DOWN' otherwise.
Implement the following methods:
set(key: str, value: str) -> list
: Set a key-value pair on the appropriate instance. Returns
[success (0/1), message, totalDelay]
. Message is
'OK'
on success,
'INSTANCE_DOWN'
or
'CIRCUIT_OPEN'
on failure.
get(key: str) -> list
: Get the value for a key from the appropriate instance. Returns
[success (0/1), value or 'NULL' or error message, totalDelay]
.
delete(key: str) -> list
: Delete a key from the appropriate instance. Returns
[success (0/1), 'OK'/'NOT_FOUND' or error message, totalDelay]
.
markDown(instanceIndex: int) -> str
: Mark an instance as down (simulates failure). Returns
'OK'
or
'INVALID_INDEX'
.
markUp(instanceIndex: int) -> str
: Mark an instance as up (simulates recovery). Returns
'OK'
or
'INVALID_INDEX'
.
resetCircuit(instanceIndex: int) -> str
: Reset the circuit breaker for an instance, closing it and clearing the failure count. Returns
'OK'
or
'INVALID_INDEX'
.
getInstanceIndex(key: str) -> int
: Return the instance index that a given key maps to (sum of ASCII values mod
numInstances
).
isCircuitOpen(instanceIndex: int) -> int
: Return 1 if the circuit breaker for the given instance is open, 0 if closed, -1 if the index is invalid.
All instances are healthy, so every data call succeeds on its first attempt with a delay of 0. A missing key is still a successful call: get returns 'NULL' and delete returns 'NOT_FOUND'. With two instances, index 2 is out of range.
Key "b" maps to instance 0 and key "a" to instance 1, so the outage on instance 0 does not affect "a". The first failing get("b") makes three attempts on a down instance: the failure counter reaches 3, below the threshold of 4, and the delay is 100 + 200 = 300. The next call's first attempt brings the counter to 4 and opens the circuit, its two retries fail fast, and it reports 'CIRCUIT_OPEN' with the same 300 delay. Marking the instance up leaves the circuit open, and after resetCircuit the value stored before the outage is readable again.
Constraints & Assumptions
1 <= numInstances <= 10
0 <= maxRetries <= 5
1 <= baseDelay <= 1000
1 <= failureThreshold <= 10
Keys are non-empty strings of lowercase English letters.
Values are non-empty strings of lowercase English letters and digits.
At most
1000
operations will be performed.
An instance that is marked down keeps its data. Once it is up and its circuit is closed, keys written earlier are readable again.
What a Strong Answer Covers Guidance
How state is split across instances, and why a failing instance cannot affect keys that hash to another one.
The retry loop: how many attempts a call makes, which attempts add a delay, and the total delay of a call that fails on every attempt.
The order of checks inside one attempt, and exactly when the failure counter rises, resets, or opens the circuit.
The return value on every path, including missing keys, invalid indices and a circuit that opens partway through a call.
Per-call time complexity, and how this simulated breaker differs from one a production client would use.
Follow-up Questions Guidance
How would you add a half-open state so the circuit closes on its own after a cool-down?
How would you add jitter to the backoff, and what problem does it solve when many clients fail at once?
If an instance could fail after applying a write but before replying, which of these operations are still safe to retry?
How would you make the wrapper safe to call from many threads at once?