A FastAPI service that ingests financial transactions and returns rolling 60-second aggregate statistics, built entirely on in-process memory with O(1) time and memory for both endpoints.
- Python 3.12+
- A virtual environment (recommended)
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install -r requirements.txtuvicorn src.main:app --reloadThe API is available at http://localhost:8000.
Interactive docs: http://localhost:8000/docs
pytestAll tests must exit with code 0. To see verbose output:
pytest -vRecord a transaction. The timestamp is the time the transaction occurred
(not the time the request is sent). Late-arriving past timestamps within the
last 60 seconds are accepted.
Request body
{
"amount": 12.3,
"timestamp": 1478192204000
}| Field | Type | Description |
|---|---|---|
amount |
double | Transaction value (finite; positive, zero, or negative) |
timestamp |
long | Transaction time — Unix epoch milliseconds, UTC |
Responses
| Status | Meaning |
|---|---|
201 |
Transaction accepted and stored |
204 |
Transaction discarded — timestamp older than 60 s |
422 |
Validation error — missing or invalid field |
Example
curl -X POST http://localhost:8000/transactions \
-H "Content-Type: application/json" \
-d '{"amount": 12.3, "timestamp": 1478192204000}'Return aggregate statistics computed over all transactions whose timestamp
falls within the last 60 seconds at the instant the request is processed.
Executes in O(1) time and memory.
Response body
{
"sum": 1000.0,
"avg": 100.0,
"max": 200.0,
"min": 50.0,
"count": 10
}| Field | Type | Description |
|---|---|---|
sum |
double | Total sum of transaction amounts in the window |
avg |
double | Arithmetic mean of amounts in the window |
max |
double | Highest single amount in the window |
min |
double | Lowest single amount in the window |
count |
long | Number of transactions in the window |
Returns all-zero / zero-count when no transactions are in the window.
Example
curl http://localhost:8000/statistics- No database — all state lives in the running process's heap memory. Data is lost on restart; this is acceptable for live monitoring.
- O(1) complexity — a fixed 60-slot circular bucket array is used. Each slot holds pre-aggregated stats for one second. Reads always iterate exactly 60 slots regardless of transaction volume.
- Thread safety — a single
asyncio.Lockguards the shared bucket array. Seedesign.mdfor full design decisions and trade-offs.