Project Workshop — Ride-Hailing Backend Service
This is a portfolio submission, not a copy-and-run tutorial. A reviewer must be able to clone it, configure it without guessing, execute the critical path, observe a deliberate failure, run the tests, and understand the most important…
- What you are building
- Architecture
- Acceptance criteria
- Suggested repository structure
- Build plan: vertical slices
FastAPI · Redis · GEO · Pub/Sub · Redlock
Expected effort: 25–40 focused hours · Minimum meaningful tests: 12What you are building
This is a portfolio submission, not a copy-and-run tutorial. A reviewer must be able to clone it, configure it without guessing, execute the critical path, observe a deliberate failure, run the tests, and understand the most important design decision from the README.
Architecture
Critical interaction
Ownership table
| Boundary | Owns | Must not own |
|---|---|---|
| Interface | Parsing, protocol validation, identity extraction, status or presentation mapping | Core business invariants |
| Application/domain | Authorization inputs, state transitions, orchestration, transaction intent | Framework globals or raw transport objects |
| Repository/gateway | One persistence or external protocol, bounded retries, error translation | Product policy |
| Background/UI projection | Recoverable derived state and delivery progress | Hidden authoritative truth |
| Operations | Configuration, health, deployment, telemetry, recovery | Business decisions encoded only in dashboards |
Acceptance criteria
| ID | Required behavior | Evidence |
|---|---|---|
| AC-1.1 | String: SET/GET/INCR/SETEX produces the specified behavior inside Data structures | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.2 | Hash: HSET/HGET/HGETALL for objects produces the specified behavior inside Data structures | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.3 | List: LPUSH/RPUSH/BLPOP for queues produces the specified behavior inside Data structures | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.4 | Set: SADD/SINTER/SUNION/SDIFF produces the specified behavior inside Data structures | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.5 | Sorted Set: ZADD/ZRANGEBYSCORE for leaderboards produces the specified behavior inside Data structures | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-1.6 | HyperLogLog and Bitmaps produces the specified behavior inside Data structures | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.1 | cache-aside (lazy) with TTL produces the specified behavior inside Caching strategies | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.2 | write-through: cache + DB simultaneously produces the specified behavior inside Caching strategies | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.3 | write-behind (async DB writes) produces the specified behavior inside Caching strategies | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-2.4 | cache stampede prevention: mutex lock + probabilistic expiry produces the specified behavior inside Caching strategies | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.1 | Redlock algorithm produces the specified behavior inside Distributed locking | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.2 | Python redlock-py implementation produces the specified behavior inside Distributed locking | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.3 | SET NX PX pattern produces the specified behavior inside Distributed locking | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-3.4 | fencing tokens for safety produces the specified behavior inside Distributed locking | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.1 | PUBLISH/SUBSCRIBE/PSUBSCRIBE produces the specified behavior inside Pub/Sub & Redis GEO | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.2 | aioredis async pub/sub produces the specified behavior inside Pub/Sub & Redis GEO | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-4.3 | GEOADD/GEOSEARCH for nearby locations produces the specified behavior inside Pub/Sub & Redis GEO | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.1 | EXPIRE/PEXPIRE/TTL and lazy plus active expiry produces the specified behavior inside Expiry, eviction & transactions | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.2 | noeviction/allkeys-lru/volatile-lru/allkeys-lfu/random/ttl policies produces the specified behavior inside Expiry, eviction & transactions | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.3 | MULTI/EXEC queued atomic execution produces the specified behavior inside Expiry, eviction & transactions | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.4 | WATCH optimistic compare-and-set produces the specified behavior inside Expiry, eviction & transactions | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.5 | pipeline batching vs transaction atomicity produces the specified behavior inside Expiry, eviction & transactions | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
| AC-5.6 | maxmemory sizing and eviction telemetry produces the specified behavior inside Expiry, eviction & transactions | Automated assertion, reproducible command, plan, trace, metric, or accessible browser check |
Suggested repository structure
1project/2├── app/3│ ├── main.py4│ ├── api/{routes.py,dependencies.py}5│ ├── domain/{models.py,services.py,errors.py}6│ ├── repositories/7│ ├── schemas/8│ ├── workers/9│ └── observability.py10├── migrations/11├── tests/{unit,integration,contract}/12├── pyproject.toml13├── Dockerfile14└── compose.yamlBuild plan: vertical slices
| Milestone | Capability | First implementation | Exit condition |
|---|---|---|---|
| 1 | Data structures | String: SET/GET/INCR/SETEX; Hash: HSET/HGET/HGETALL for objects; List: LPUSH/RPUSH/BLPOP for queues | Demonstration plus focused tests |
| 2 | Caching strategies | cache-aside (lazy) with TTL; write-through: cache + DB simultaneously; write-behind (async DB writes) | Demonstration plus focused tests |
| 3 | Distributed locking | Redlock algorithm; Python redlock-py implementation; SET NX PX pattern | Demonstration plus focused tests |
| 4 | Pub/Sub & Redis GEO | PUBLISH/SUBSCRIBE/PSUBSCRIBE; aioredis async pub/sub; GEOADD/GEOSEARCH for nearby locations | Demonstration plus focused tests |
| 5 | Expiry, eviction & transactions | EXPIRE/PEXPIRE/TTL and lazy plus active expiry; noeviction/allkeys-lru/volatile-lru/allkeys-lfu/random/ttl policies; MULTI/EXEC queued atomic execution | Demonstration plus focused tests |
| 6 | Hardening and delivery | Security, recovery, telemetry, performance, documentation | Full acceptance suite and recorded demonstration |
For each milestone, first create a failing acceptance test or a reproducible command. Implement the thinnest path to an observable result, add the nearest durable invariant, inject one expected failure, and refactor only after evidence protects the behavior.
Reference vertical slice
1import secrets2from redis.asyncio import Redis3
4async def cached(redis: Redis, key: str, loader):5 if value := await redis.get(key):6 return decode(value)7 lock_key = f"lock:{key}"8 token = secrets.token_hex(16)9 if await redis.set(lock_key, token, nx=True, px=5_000):10 try:11 value = await loader()12 await redis.set(key, encode(value), ex=300 + secrets.randbelow(30))13 return value14 finally:15 await redis.eval(COMPARE_DELETE, 1, lock_key, token)16 await asyncio.sleep(0.05)17 return await cached(redis, key, loader)Expected result
1A cache miss is coalesced behind a token-owned lease and the stored value receives jittered expiry.Code reading
| Line | Code | Explanation |
|---|---|---|
| 1 | import secrets | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 2 | from redis.asyncio import Redis | Imports the named dependency; import executes the module once per interpreter cache and binds selected names here. |
| 4 | async def cached(redis: Redis, key: str, loader): | Defines a coroutine function; calling it creates a coroutine object and await drives its execution. |
| 5 | if value := await redis.get(key): | Evaluates the condition and enters this branch only when it is truthy. |
| 6 | return decode(value) | Returns the observable result to the caller and ends this invocation. |
| 7 | lock_key = f"lock:{key}" | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 8 | token = secrets.token_hex(16) | Computes or receives a value and binds it for the next step; the referenced object remains separate from the name. |
| 9 | if await redis.set(lock_key, token, nx=True, px=5_000): | Evaluates the condition and enters this branch only when it is truthy. |
| 10 | try: | Defines failure translation or cleanup that must run around the protected operation. |
| 11 | value = await loader() | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
| 12 | await redis.set(key, encode(value), ex=300 + secrets.randbelow(30)) | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
| 13 | return value | Returns the observable result to the caller and ends this invocation. |
| 14 | finally: | Defines failure translation or cleanup that must run around the protected operation. |
| 15 | await redis.eval(COMPARE_DELETE, 1, lock_key, token) | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
| 16 | await asyncio.sleep(0.05) | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
| 17 | return await cached(redis, key, loader) | Starts or resumes asynchronous I/O and yields control until the awaited operation completes. |
Risk register
| Area | Failure to reproduce | Required design response |
|---|---|---|
| Data structures | Large aggregate keys create latency spikes, replication cost, and difficult resharding. | Choose the type that performs the needed update in one bounded command. |
| Caching strategies | Delete/update races can repopulate stale values; cache correctness is a protocol. | Document key version, TTL jitter, negative caching, and source-of-truth behavior. |
| Distributed locking | A paused client can outlive its lease and still act; ownership tokens alone do not stop stale writes. | Prefer database constraints for data invariants; use leases for bounded coordination and add fencing for critical resources. |
| Pub/Sub & Redis GEO | Subscriber disconnection loses Pub/Sub messages; GEO distance is not a road-routing engine. | Use Streams or Kafka when replay is required and model location freshness separately. |
| Expiry, eviction & transactions | Using noeviction without handling write failures or assuming a pipeline is transactional causes production-only faults. | Select eviction by whether all keys are disposable, set memory headroom for replication/persistence, and use Lua for a multi-step atomic decision. |
Engineering checklist for this stack
- To do: protect invariants with constraints and transactions
- To do: parameterize every value
- To do: measure representative plans and memory
- To do: bound cardinality and retention
- To do: document recovery, backup, or rebuild behavior
Test strategy
Implement at least 12 meaningful cases. A long list of shallow happy-path tests does not satisfy the requirement.
| Risk class | Minimum | Examples |
|---|---|---|
| Happy path and contract | 2 | Correct output, status/schema, durable state |
| Validation and boundaries | 2 | Empty, malformed, extreme, unsupported transition |
| Authorization or trust boundary | 1 | Missing identity, wrong tenant/role, injection or unsafe content |
| Failure and recovery | 2 | Timeout, retry, rollback, reconnect, dependency outage |
| Duplicate or concurrency | 1 | Same identity twice, racing update, redelivery |
| Performance and operations | 4 | Query bound, lag, p95, resource limit, telemetry |
Representative test scaffold
1@pytest.mark.anyio2async def test_duplicate_request_is_idempotent(client, auth_headers):3 headers = {**auth_headers, "Idempotency-Key": "stable-1"}4 first = await client.post("/resources", json={"name": "one"}, headers=headers)5 second = await client.post("/resources", json={"name": "one"}, headers=headers)6 assert first.status_code == 2017 assert second.status_code in {200, 201}8 assert first.json()["id"] == second.json()["id"]Failure drills
- Stop the primary external dependency during the critical path. Capture the failure, cleanup, telemetry, and recovery.
- Repeat the same operation with the same stable identity. Prove one logical outcome or document why repetition is forbidden.
- Crash after durable state changes but before the response, acknowledgement, or projection. Re-run and reconcile.
- Submit the largest supported input and one slightly larger input.
- Remove one permission and prove denial without state change or information leakage.
- Roll back the change or restore the dependency, then run a smoke test and reconciliation check.
Performance experiment
State the dataset, payload distribution, concurrency, rate, duration, cache state, and resource limits before measuring. Publish p50, p95, p99, throughput, error rate, and the technology-specific correctness signal such as query count, consumer lag, duplicate effects, rendered updates, token cost, or recall. Change one variable at a time and retain raw output.
Submission package
- Complete source with a locked/reproducible environment.
- README.md with problem, architecture, setup, commands, configuration, assumptions, and trade-offs.
- Acceptance and risk-focused tests with a short explanation of what mocks intentionally do not cover.
- One design record explaining the most consequential choice and a rejected alternative.
- Security notes, sample non-secret configuration, and cleanup commands.
- A demonstration record: terminal transcript, screenshots, trace, query plan, or metrics dashboard.
- A 5–8 minute walkthrough following input → validation → state → failure → evidence.
Grading rubric
| Dimension | Weight | Full-credit evidence |
|---|---|---|
| Product behavior | 25 | Acceptance criteria pass through real public boundaries |
| Architecture and ownership | 20 | Responsibilities and state authority are explicit |
| Tests and recovery | 20 | Important negative, duplicate, concurrent, and outage cases pass |
| Security and data correctness | 15 | Least privilege, validation, constraints, and secret handling are demonstrated |
| Performance and operations | 10 | Reproducible measurement, useful telemetry, and rollback/recovery |
| Documentation and explanation | 10 | A new reviewer can reproduce and defend the result |
Mastery check
How well can you recall this?
Finished this lesson?