Skip to content

renzrollon/statistics

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Realtime Transaction Statistics API

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.


Prerequisites

  • Python 3.12+
  • A virtual environment (recommended)

Install

python -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
pip install -r requirements.txt

Run

uvicorn src.main:app --reload

The API is available at http://localhost:8000. Interactive docs: http://localhost:8000/docs


Test

pytest

All tests must exit with code 0. To see verbose output:

pytest -v

API Reference

POST /transactions

Record 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}'

GET /statistics

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

Design notes

  • 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.Lock guards the shared bucket array. See design.md for full design decisions and trade-offs.

About

Exercise for statistics using Python and Spec Driven Development

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages