add TECHNICAL_DECISIONS

This commit is contained in:
Meghdad committed 2026-07-23 06:44:10 +03:30
1 parent db57e0e4a2
commit ab0ee3f209
2 files changed
+697

No files matched your search

+2
View File
@@ -2,6 +2,8 @@
یک مایکروسرویس stateless و کم‌تأخیر برای انتخاب انباری که **تمام SKUهای سفارش** را موجود دارد و با توجه به هزینه حمل، فاصله، ترافیک، ظرفیت ناوگان و SLA بهترین نتیجه را می‌دهد. سرویس برای ۳۳ هاب طراحی شده، اما سقف کاندیدا قابل تنظیم است.
شرح کامل تصمیم‌های فنی، منطق الگوریتم، دلیل و زمان استفاده از Redis، گزینه‌های ردشده و محدودیت‌های فعلی در [Technical Decisions](docs/TECHNICAL_DECISIONS.md) قرار دارد.
## اجرای سریع با Docker Compose
پیش‌نیاز: Docker و Docker Compose.
+695
View File
@@ -0,0 +1,695 @@
# Warehouse Allocation — Technical Decisions and Rationale
This document explains the significant product, algorithm, architecture, storage, API, consistency, performance, deployment, and testing decisions made in this project. It describes the current implementation, why each choice was made, when it is appropriate, and when it should be replaced.
## 1. Problem interpretation
The service must choose one warehouse for an e-commerce order while considering:
- whether that warehouse has every requested SKU in the required quantity;
- transportation cost from each candidate warehouse to the customer;
- expected delivery time;
- road traffic;
- fleet priority and capacity;
- handling time;
- the promised delivery time;
- concurrent orders that may consume inventory;
- the 200 ms response-time objective.
The current version performs **single-warehouse fulfillment**. One warehouse must contain the complete order. It does not split an order between warehouses.
### Why single-warehouse fulfillment?
Split fulfillment changes the optimization problem substantially. It introduces additional shipments, packaging costs, partial-delivery rules, customer-experience penalties, and a combinatorial search over warehouse subsets. None of those costs were defined in the challenge.
The single-warehouse model is therefore safer and deterministic for the supplied requirements. If split fulfillment becomes a requirement, the problem should be modeled as min-cost flow or mixed-integer optimization rather than added as a small condition to the current scorer.
## 2. High-level architecture
```text
Order service / API client
|
| POST /v1/allocations
v
Stateless FastAPI instances
1. validate request
2. query inventory projection
3. remove infeasible warehouses
4. rank feasible warehouses
5. optionally reserve inventory
|
| pipelined reads / atomic Lua reservation
v
Redis inventory projection
^
| inventory events, CDC, or reconciliation
|
Transactional inventory source of truth
```
The code is divided into four boundaries:
- `domain/models.py`: validated business inputs and outputs;
- `domain/optimizer.py`: pure allocation and ranking rules;
- `application.py`: orchestration of inventory lookup, ranking, and reservation;
- `infrastructure/inventory.py`: in-memory and Redis storage adapters;
- `api.py`: HTTP, dependency wiring, health checks, errors, and metrics.
### Why separate these layers?
The allocation rules should not depend on FastAPI, Redis, or Kubernetes. This separation:
- makes the algorithm testable without a network or database;
- keeps infrastructure replacement possible;
- prevents HTTP concerns from leaking into business rules;
- supports SOLID's dependency inversion principle;
- makes failures easier to locate.
This is a practical clean/hexagonal architecture, without adding unnecessary abstractions for such a small service.
## 3. Why FastAPI and Python?
FastAPI was selected because it provides:
- request validation and JSON serialization through Pydantic;
- generated OpenAPI and Swagger documentation;
- asynchronous Redis and HTTP support;
- low implementation complexity for a challenge project;
- strong type annotations;
- good compatibility with containerized stateless workloads.
Python is suitable because the current algorithm evaluates only tens of warehouses. Its runtime cost is insignificant compared with network and storage latency. The domain algorithm is `O(W × S)`, where `W` is the warehouse count and `S` is the number of order SKUs.
### When would another runtime be preferable?
Go, Rust, or Java may be preferable if profiling shows that a single instance must sustain much higher CPU-bound throughput, strict tail latency is required under very high concurrency, or the organization already has stronger operational standards for one of those ecosystems. The service boundaries and algorithm can remain the same.
## 4. Why is the service stateless?
No allocation state required by another request is stored in a FastAPI process. Shared inventory is held in Redis or the transactional inventory system.
Statelessness allows:
- any request to be served by any replica;
- horizontal scaling through Kubernetes HPA;
- safe pod replacement;
- rolling deployments;
- no sticky sessions;
- predictable recovery after an instance failure.
The in-memory inventory adapter is only for tests and local development. It is explicitly not suitable for multiple replicas because each process would have a different inventory view.
## 5. When and why Redis is used
Redis is used as a **fast inventory projection**. Each warehouse is represented by a Redis hash:
```text
key: inventory:{warehouseId}
field value
SKU-RED-42 20
SKU-BLUE-10 7
```
For an allocation request, the service performs one non-transactional Redis pipeline containing an `HMGET` for every candidate warehouse. This reduces network round trips while checking all requested SKUs.
### Why Redis?
The allocation path needs repeated point lookups by warehouse and SKU. Redis provides:
- in-memory read latency;
- hashes that naturally represent warehouse stock;
- pipelining for all 33 warehouses in one network exchange;
- atomic Lua execution for multi-SKU reservations;
- shared state across stateless service replicas;
- straightforward expiration or reservation extensions in future versions.
Redis is valuable when inventory reads are much more frequent than authoritative inventory updates and when the response-time budget is tight.
### When should Redis be used?
Use Redis:
- on the synchronous allocation path;
- as a read-optimized projection of available inventory;
- for short-lived reservations;
- when multiple API replicas require the same low-latency inventory view;
- when the source database cannot satisfy the required tail latency at peak load.
### When should Redis not be used?
Do not treat Redis as the only permanent inventory ledger when:
- financial or stock auditability is required;
- inventory changes must be preserved even after total cache loss;
- cross-domain transactions are required;
- long-term historical queries are needed;
- strict authoritative consistency is more important than latency.
In production, a transactional database or inventory service should remain the source of truth. Redis should be rebuilt from events, CDC, or reconciliation.
### Why not query PostgreSQL for every allocation?
PostgreSQL can provide stronger transactional guarantees and may be sufficient at smaller scale. However, repeatedly querying stock for up to 33 warehouses and many SKUs increases database load and makes a 200 ms tail-latency target harder to protect during traffic spikes.
PostgreSQL remains a good source of truth. Redis is selected for the hot read path, not because relational databases are unsuitable for inventory.
### Why not Elasticsearch?
Inventory validation is an exact key-and-quantity lookup, not full-text search. Elasticsearch adds indexing delay, eventual consistency, and operational complexity without improving this access pattern.
### Redis failure behavior
Redis connection and command timeouts are intentionally short. If Redis is unavailable, the service returns HTTP 503 with `Retry-After: 1`.
It does not silently allocate from stale local state because that could produce incorrect logistics decisions or overselling.
## 6. Inventory consistency and reservation
Reading available stock and later decrementing it creates a race:
```text
Request A reads quantity 1
Request B reads quantity 1
Request A reserves quantity 1
Request B also attempts to reserve quantity 1
```
The Redis adapter solves the local race with one Lua script. The script:
1. reads every requested SKU in the selected warehouse;
2. verifies that every quantity is sufficient;
3. decrements all quantities only if every check succeeds;
4. performs all steps atomically inside Redis.
This prevents partial reservation and overselling through concurrent instances of this service.
### Why Lua rather than several Redis commands?
A transaction composed in the application would require additional coordination and retry handling. A Lua script executes next to the data and guarantees that no other Redis command observes an intermediate state.
### Why does the service retry another warehouse?
The feasibility read is optimistic. Another order may reserve the best warehouse before the current request reaches the reservation step. If reservation of the first-ranked warehouse fails, the service tries the remaining feasible warehouses in score order.
This improves success rate without weakening atomicity.
### What consistency problem remains?
Atomic Redis reservation does not create a distributed transaction with the authoritative inventory database or the order service. A production design should use:
- a transactional source of truth;
- an Outbox or CDC stream for inventory projection updates;
- versioned, idempotent events;
- a Saga for confirmation and compensation;
- reservation TTLs;
- periodic reconciliation between Redis and authoritative stock.
### Request ID and idempotency
The current `requestId` is a correlation identifier. It is not yet an idempotency key. Repeating a request with `reserveInventory: true` performs another reservation.
Before production use, either the order orchestrator must guarantee idempotency or the service must store a reservation result keyed by `requestId`, return the prior result for retries, and apply an appropriate TTL.
## 7. Warehouse allocation algorithm
The algorithm is a deterministic **constraint filter followed by multi-criteria ranking**.
### Inputs
The important inputs are:
- customer coordinates;
- order items and quantities;
- one transportation-cost record per candidate warehouse;
- traffic multiplier per warehouse;
- fleet priority per warehouse;
- handling time per warehouse;
- optional promised-delivery time;
- cost and delivery-time weights.
### Step 1: validate the request
Validation rejects:
- invalid latitude or longitude;
- empty item or warehouse lists;
- duplicate SKUs;
- duplicate warehouse cost records;
- constraints for unknown warehouses;
- negative costs, distance, time, or quantity;
- weights that do not sum to one;
- unknown JSON fields.
Rejecting unknown fields is intentional. A misspelled logistics parameter should fail clearly instead of being ignored and causing an incorrect allocation.
### Step 2: enforce the candidate limit
The configured default is 33 candidate warehouses, matching the challenge. This is a latency guardrail. Requests above the configured maximum return a client error instead of consuming unbounded CPU or issuing an unexpectedly large Redis query.
### Step 3: inventory feasibility filter
For each warehouse:
```text
feasible =
warehouse is operational
AND available quantity of every SKU >= requested quantity
```
Warehouses that cannot fulfill the complete order are removed.
### Step 4: calculate effective cost
First, calculate raw transportation cost:
```text
rawCost =
fixedCost
+ distanceKm × costPerKm
+ surcharge
```
Then account for congestion and fleet priority:
```text
congestionCostFactor =
1 + max(trafficMultiplier - 1, 0) × 0.15
totalCost =
rawCost × congestionCostFactor / fleetPriority
```
The `0.15` coefficient models the fact that congestion increases fuel and driver cost, but normally not in direct proportion to elapsed time. It is a configurable business assumption in a future version; in the challenge implementation it is an explicit constant so the decision remains reproducible.
`fleetPriority > 1` represents preferred or faster fleet capacity and lowers the effective burden. `fleetPriority < 1` represents constrained capacity.
### Step 5: calculate estimated delivery time
```text
ETA =
(
baseDeliveryMinutes × trafficMultiplier
+ handlingMinutes
)
/ fleetPriority
```
Traffic affects travel time. Handling time covers pick, pack, staging, and loading. Fleet priority changes the expected capacity available to this order.
The final API rounds ETA to the nearest minute because the required contract returns minutes and sub-minute precision would suggest false accuracy.
### Step 6: normalize cost and time
Cost and time use different units, so they cannot be added directly. Each value is normalized relative to the feasible candidates:
```text
normalizedValue =
(value - minimumValue)
/ (maximumValue - minimumValue)
```
The best observed value becomes `0`; the worst becomes `1`.
If all candidates have the same value, the normalized result is `0` because that criterion cannot distinguish them. If only one warehouse is feasible, both normalized values are `0`.
### Why min-max normalization?
It is:
- fast;
- deterministic;
- easy to explain;
- independent of currency scale;
- suitable for a small candidate set;
- easy for reviewers and operators to reproduce.
Its limitation is sensitivity to extreme outliers. Production alternatives include percentile clipping, business-defined reference ranges, or learned utility functions.
### Step 7: SLA penalty
When ETA exceeds the promised delivery time:
```text
overrunRatio =
(ETA - promisedDeliveryMinutes)
/ promisedDeliveryMinutes
slaPenalty =
min(0.25, overrunRatio × 0.25)
```
The cap prevents the SLA term from completely erasing the configured cost/time policy. The exact coefficient and cap are business parameters and should eventually move to versioned configuration.
### Step 8: objective and optimization score
The default weights are 70% cost and 30% delivery time:
```text
objective =
costWeight × normalizedCost
+ deliveryTimeWeight × normalizedETA
+ slaPenalty
objective = min(objective, 1)
routeOptimizationScore =
100 × (1 - objective)
```
A higher score is better. The score is relative to the feasible warehouses in this request, not an absolute network-wide quality measurement.
### Step 9: deterministic tie-breaking
Candidates are ordered by:
1. lowest objective;
2. lowest total cost;
3. lowest ETA;
4. lexicographically smallest warehouse ID.
Determinism matters for reproducible tests, incident analysis, cache behavior, and consistent business results.
### Example
Assume two feasible warehouses:
| Warehouse | Effective cost | ETA |
|---|---:|---:|
| A | 100 | 120 min |
| B | 150 | 60 min |
After normalization:
| Warehouse | Normalized cost | Normalized ETA |
|---|---:|---:|
| A | 0 | 1 |
| B | 1 | 0 |
With 70% cost and 30% time:
```text
A objective = 0.7 × 0 + 0.3 × 1 = 0.3
A score = 70
B objective = 0.7 × 1 + 0.3 × 0 = 0.7
B score = 30
```
Warehouse A wins because the configured business policy values cost more than speed. Changing weights to 20% cost and 80% time makes B win.
## 8. Why not Dijkstra?
Dijkstra solves shortest paths in a weighted graph. The API already receives a cost/time matrix from each warehouse to the destination. There is no road graph in this service to traverse.
Running Dijkstra here would duplicate the responsibility of a route engine and add work without improving the warehouse choice.
Use Dijkstra, A*, contraction hierarchies, OSRM, or GraphHopper in the component that builds the route matrix from the road network. Pass the resulting distance, cost, and time into this allocation service.
## 9. Why not a genetic algorithm?
A genetic algorithm is useful for large, nonlinear search spaces where exact enumeration is too expensive. Choosing one warehouse from 33 candidates is a small finite problem. Every candidate can be evaluated directly.
Genetic algorithms would add:
- nondeterministic answers;
- tuning parameters;
- additional latency;
- harder debugging;
- no optimality benefit for this candidate count.
They may become relevant for complex multi-warehouse shipment planning, vehicle routing, loading constraints, or network-wide batch optimization.
## 10. Why not machine learning in the critical path?
ML is useful for predicting traffic, handling time, failed delivery probability, or future demand. It is not automatically a better replacement for the final allocation rule.
The selected design keeps prediction outside the critical path:
1. a traffic or operations model produces versioned estimates;
2. the estimates are supplied as `trafficMultiplier`, base delivery time, or surcharge;
3. the allocation service applies deterministic business policy.
This approach preserves explainability and allows an allocation decision to be reproduced later.
A learned ranking model should only replace the scorer after:
- sufficient labeled outcome data exists;
- offline and shadow evaluations demonstrate improvement;
- drift monitoring is available;
- business constraints remain hard constraints;
- explanations and rollback are implemented.
## 11. Customer location and the route matrix
Customer coordinates are retained in the API contract for validation, traceability, and future routing integration. The current scorer does not calculate road distance directly from latitude and longitude.
Straight-line Haversine distance is not an adequate substitute for road routing because mountains, road class, restrictions, tolls, and heavy-fleet rules affect the actual route.
The intended production flow is:
1. a route-matrix component receives customer coordinates;
2. it calculates route distance, ETA, and cost from each warehouse;
3. this service receives those values in `transportationCosts`;
4. this service combines routing data with inventory and business constraints.
This separation prevents duplicated route calculations and allows route-matrix responses to be cached briefly by destination area and time window.
## 12. API decisions
### Why `POST /v1/allocations`?
The request contains a nontrivial decision payload and may optionally reserve inventory. `POST` correctly represents calculation with possible side effects.
### Why one endpoint for quote and reservation?
`reserveInventory: false` returns a quote without mutation. `true` performs atomic reservation. This keeps the challenge API compact while allowing tests and planning calls.
In a larger production API, separate `/quotes` and `/reservations` resources may be clearer, especially if reservation lifecycle, cancellation, and expiry are added.
### Why camelCase JSON?
The external contract uses language-neutral camelCase while Python code remains idiomatic snake_case. Pydantic aliases perform the mapping consistently.
### Why include a score breakdown?
The required four output values are returned, and the response additionally exposes:
- normalized cost;
- normalized time;
- SLA penalty;
- feasible warehouse count.
The breakdown improves explainability and incident analysis. It can be hidden behind an internal/debug contract later if exposing business coefficients is undesirable.
### Error-status decisions
- `422`: schema or field validation failure;
- `400`: candidate count exceeds the configured guardrail;
- `409`: no warehouse can satisfy the order, or stock changed before reservation;
- `503`: inventory dependency is unavailable;
- `401`: configured inventory-admin token is missing or invalid.
`409` is used for inventory feasibility because the request is structurally valid but conflicts with current stock state.
## 13. Latency decisions
The implementation protects the 200 ms objective through:
- `O(W × S)` bounded work;
- a maximum candidate count;
- one Redis pipeline rather than serial reads;
- an atomic server-side reservation script;
- asynchronous I/O;
- short Redis timeouts;
- no route-engine or ML call inside the synchronous scorer;
- no local persistent state;
- deterministic computation without iterative search.
The benchmark warms up HTTP connections, sends 1,000 allocation requests for 33 warehouses, and fails if p95 reaches 200 ms or any request fails.
The recorded local reference for one process with the in-memory adapter and concurrency 25 was:
```text
throughput = 500.7 requests/second
mean = 48.1 ms
p95 = 124.6 ms
failures = 0
```
This is a development measurement, not a production capacity guarantee. Production testing must include:
- the real Redis deployment;
- representative SKU counts and payload sizes;
- TLS and ingress;
- cross-zone network latency;
- realistic traffic distributions;
- noisy-neighbor conditions;
- pod autoscaling behavior.
## 14. Database and persistence decisions
Redis is configured with AOF in Docker Compose to improve local durability, but local Compose persistence is not a substitute for an authoritative production inventory database.
A recommended production storage model is:
| Concern | Recommended storage |
|---|---|
| Authoritative stock | transactional inventory database/service |
| Order and reservation audit | relational database or event log |
| Fast availability projection | Redis |
| Historical analytics | warehouse/lake |
| Logs and traces | observability platform |
PostGIS is not currently needed because the service receives route-matrix data. It becomes useful if the service must discover nearby warehouses by coordinates before route calculation.
## 15. Container decisions
The Docker image:
- uses a builder stage to create wheels;
- uses a small Python slim runtime;
- runs as UID/GID 10001 rather than root;
- disables bytecode and unbuffered-output surprises;
- has no source build toolchain in the runtime stage;
- exposes only port 8080.
Docker Compose:
- runs the API and Redis;
- waits for Redis health;
- uses an API readiness health check;
- mounts persistent Redis data;
- uses a read-only API filesystem and temporary `/tmp`;
- enables `no-new-privileges`.
These choices reduce image size and runtime attack surface.
## 16. Kubernetes decisions
The Kubernetes example contains:
- two initial replicas for availability;
- a Service for stable routing;
- readiness and liveness probes with different purposes;
- CPU and memory requests/limits;
- a non-root, read-only security context;
- an HPA from 2 to 20 replicas;
- a conservative scale-down stabilization window.
### Why different readiness and liveness checks?
Liveness only verifies that the process is functioning. It deliberately avoids Redis so a Redis outage does not cause every API pod to restart.
Readiness checks Redis. An instance that cannot serve correct allocations should be removed from request routing until the dependency recovers.
### Why CPU-based HPA?
CPU is available in a basic cluster and correlates with request parsing and scoring work. A production service should preferably scale on request rate, concurrency, or latency using Prometheus/custom metrics because dependency wait time is not always reflected in CPU.
## 17. Observability decisions
The service exposes:
- `X-Process-Time-Ms` for quick request inspection;
- a Prometheus request counter grouped by result;
- an allocation-duration histogram with buckets around the 200 ms objective;
- liveness and readiness endpoints;
- structured domain error codes in important failure responses.
The next production additions should be:
- OpenTelemetry traces;
- correlation of `requestId` in logs and spans;
- Redis command latency;
- feasible-candidate count distribution;
- reservation-race count;
- SLA-violation prediction and actual delivery outcomes;
- dashboards and alerts for p95/p99 and error budgets.
## 18. Testing decisions
Tests are split by responsibility:
- optimizer tests verify weights, traffic, SLA, filtering, and validation;
- application tests verify quoting, reservation fallback, and candidate limits;
- in-memory repository tests verify concurrent reservation behavior;
- Redis adapter tests verify pipelining, reservation, failures, and readiness;
- API tests verify the JSON contract, errors, inventory mutation, health, and metrics.
The CI coverage threshold is 85%. The current suite contains 24 tests and reports more than 94% total coverage.
Coverage is a guardrail, not proof of correctness. Important business scenarios should remain explicit tests even if the same lines are already covered.
## 19. CI/CD decisions
GitHub Actions performs:
1. dependency installation;
2. Ruff lint and formatting verification;
3. strict mypy type checking;
4. unit and integration tests;
5. coverage artifact generation;
6. Docker image build;
7. optional SonarQube scan with quality-gate waiting.
The image is built but not automatically pushed or deployed because no registry, environment, release policy, or deployment authorization was supplied.
Production delivery should add:
- a locked dependency process;
- software-bill-of-materials generation;
- dependency and container vulnerability scanning;
- signed images;
- registry push for protected branches/tags;
- staged deployment;
- smoke tests and automated rollback.
## 20. Security decisions
The inventory update endpoint can require `X-Admin-Token`. Docker Compose enables it for local demonstration.
This is intentionally minimal. Production should use:
- private network exposure for inventory ingestion;
- service identity through mTLS, workload identity, or signed JWTs;
- secrets from a secret manager;
- authorization scopes;
- rate limiting and payload-size limits at ingress;
- audit logs for inventory changes;
- no static shared token in deployment manifests.
Unknown input fields and constrained numeric ranges reduce accidental or malicious resource usage.
## 21. Important assumptions
The current design assumes:
- transportation cost and base ETA are trusted inputs;
- traffic and fleet multipliers are produced by an authorized upstream source;
- all monetary values in one request use the same currency and unit;
- one warehouse must fulfill the complete order;
- there are no temperature, hazardous-goods, seller, or legal-region constraints yet;
- warehouse inventory hashes contain nonnegative integer quantities;
- request IDs are unique for tracing but are not enforced as idempotency keys;
- the business accepts relative scoring between feasible candidates.
If any assumption changes, the model and decision policy must be versioned rather than silently reinterpreting existing fields.
## 22. Known limitations and next decisions
Before production rollout, the following decisions remain:
1. Define the authoritative inventory database and reservation lifecycle.
2. Add idempotency semantics and reservation TTL/cancellation.
3. Move business coefficients and weights into versioned policy configuration.
4. Define currency units and decimal/rounding rules; use integer minor units for money.
5. Add route-matrix integration and cache policy.
6. Decide whether split shipments are allowed and model their penalties.
7. Add warehouse capability constraints such as cold chain or hazardous goods.
8. Run load tests against production-like Redis, ingress, and Kubernetes.
9. Add tracing, dashboards, SLOs, and alert thresholds.
10. Define authentication and authorization for every endpoint.
These are intentionally documented rather than hidden behind placeholder code. Each one can materially change correctness, operations, or business behavior.