Build a Log Collection REST Service for a Fleet of Cameras
System DesignModel answerLast updated
Design and code a small HTTP service where cameras push log entries and users fetch them by camera, time range, or severity, with validation, status codes, and thread safety.
Camera Log Gateway
A fleet of cameras emits log entries. Between the cameras and the people who want to inspect those logs sits a middle-tier HTTP service, and you are asked to build it.
- Cameras (or tests pretending to be cameras) push log entries to the service.
- Users query the service to read those entries back.
- How logs are produced on the device is out of scope. Test code will generate fake logs and call your endpoints.
You write the server yourself in a language and lightweight HTTP framework of your choice (Flask or similar is fine). That covers routing, request parsing, validation, response bodies, and status codes, plus whatever in-memory storage is needed to answer queries. Persistence beyond the process lifetime is not required unless you are asked to add it.
What to produce
- An endpoint design: paths, methods, request and response formats.
- A working implementation of at least:
- an endpoint for a camera to submit log entries,
- an endpoint for a user to fetch logs for a camera, with optional time-range filtering,
- an endpoint for a user to fetch the most recent entries or filter by severity (or a similar third call).
- Validation and error handling with correct HTTP status codes.
- A storage layout that supports the queries efficiently and returns results in a defined order.
- Thread-safe handling of concurrent requests.
- A few tests that push fake logs through the API and check both the happy paths and the error paths.
Points to settle up front
State your assumptions explicitly, for instance:
- Fields of a log entry (timestamp, severity, message) and whether submissions are single or batched.
- Which queries are needed: by camera, by time range, latest N, by severity.
- How to treat unknown cameras, malformed entries, and duplicate submissions.
- Maximum response size and whether results are paginated.
- Whether authentication or per-user access control is in scope.
Hints
Hint 1
Start by writing down the resource model: a camera owns an ordered collection of log entries. Let the URLs reflect that, for example POST and GET on a path containing the camera id.
Hint 2
Decide on one validation function that returns either a clean entry or a list of errors, and map outcomes to codes: 201 for created, 400 for malformed input, 404 for an unknown camera on reads, 409 or idempotent 200 for duplicates.
Hint 3
Keep each camera's entries sorted by timestamp so a time-range query is two binary searches plus a slice. Guard the shared structure with a lock, and keep the critical section small.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model the system as cameras owning append-mostly, time-ordered lists of log entries. Expose a small REST surface, validate every input at the boundary, keep per-camera data sorted by timestamp so range reads are cheap, and protect shared state with a lock.
Assumptions (stated up front)
- A log entry is
{timestamp, severity, message}. Timestamp is an integer of epoch milliseconds (or ISO-8601 parsed to that). Severity is one ofDEBUG, INFO, WARN, ERROR. Message is a non-empty string with a length cap (say 4 KB). - Cameras may submit a batch (a list) in one request, which cuts per-request overhead.
- Reads are by camera, optionally with
start/end(inclusive start, exclusive end),severity, andlimit. - Duplicates are identified by
(camera_id, timestamp, severity, message)or by an optional client-suppliedentry_id. Resubmission is treated as idempotent: ignored, and reported in the response. - Authentication is out of scope for the exercise, but I would mention it as a follow-up (API key per camera, user tokens scoped to cameras).
Endpoint design
| Method and path | Purpose | Success | Errors |
|---|---|---|---|
POST /cameras/{id}/logs | Camera pushes one or many entries | 201 with {accepted, duplicates} | 400 malformed, 413 too large, 415 wrong content type |
GET /cameras/{id}/logs?start=&end=&severity=&limit=&cursor= | User reads entries in timestamp order | 200 with {entries, next_cursor} | 400 bad params, 404 unknown camera |
GET /cameras/{id}/logs/latest?n= | Most recent N entries | 200 | 400, 404 |
Camera registration can be implicit (first valid push creates the camera) or explicit via PUT /cameras/{id}. Implicit is simpler for the exercise; explicit gives you a clean 404 for typos on write too. I would pick implicit and say why.
Storage layout
cameras: dict[str, CameraLog]
class CameraLog:
timestamps: list[int] # sorted
entries: list[dict] # parallel to timestamps
seen: set[tuple] # dedupe keys
- Insert uses
bisect.insort-style placement (bisect_righton timestamps). Cameras mostly send in order, so this is almost always an append: O(1) amortized, O(n) worst case for late arrivals due to list shifting. - Range query:
lo = bisect_left(ts, start),hi = bisect_left(ts, end), then sliceentries[lo:hi]. Cost is O(log n + k) where k is the result size. - Severity filter is applied while scanning the slice. If severity-only queries over huge ranges are hot, add a per-severity index (a second sorted list per level).
- Equal timestamps are ordered by arrival, which
bisect_rightpreserves, so results are deterministic.
If the data grows beyond memory, the same shape maps to a table with a composite index on (camera_id, timestamp), or a time-partitioned store.
Thread safety
Flask's dev server and most WSGI servers handle requests on multiple threads. Concurrent insort on the same list is a data race at the logical level, even with the GIL, because check-then-insert sequences (dedupe plus insert) are not atomic.
- Use one
threading.Lockfor the camera map (creation of new cameras) and a per-camera lock for inserts and reads of that camera. This avoids one hot camera blocking all others. - Readers can take the lock only long enough to find indices and copy the slice, then serialize to JSON outside the lock.
- Mention the alternative: a single global
RLockis correct and simpler, and is fine for a screen; per-camera locks are the upgrade.
Reference implementation (Flask)
import threading
from bisect import bisect_left, bisect_right
from flask import Flask, request, jsonify
app = Flask(__name__)
SEVERITIES = {"DEBUG", "INFO", "WARN", "ERROR"}
MAX_BATCH, MAX_LIMIT, MAX_MSG = 1000, 1000, 4096
class CameraLog:
def __init__(self):
self.ts, self.entries, self.seen = [], [], set()
self.lock = threading.Lock()
cameras, cameras_lock = {}, threading.Lock()
def validate_entry(e):
if not isinstance(e, dict): return None, "entry must be an object"
t, s, m = e.get("timestamp"), e.get("severity"), e.get("message")
if not isinstance(t, int) or isinstance(t, bool) or t < 0:
return None, "timestamp must be a non-negative integer"
if s not in SEVERITIES: return None, "invalid severity"
if not isinstance(m, str) or not m or len(m) > MAX_MSG:
return None, "invalid message"
return {"timestamp": t, "severity": s, "message": m}, None
@app.post("/cameras/<cid>/logs")
def push(cid):
body = request.get_json(silent=True)
if body is None: return jsonify(error="JSON body required"), 400
items = body if isinstance(body, list) else [body]
if not items or len(items) > MAX_BATCH:
return jsonify(error="batch size out of range"), 400
clean = []
for i, it in enumerate(items):
e, err = validate_entry(it)
if err: return jsonify(error=err, index=i), 400 # all-or-nothing
clean.append(e)
with cameras_lock:
cam = cameras.setdefault(cid, CameraLog())
accepted = dup = 0
with cam.lock:
for e in clean:
key = (e["timestamp"], e["severity"], e["message"])
if key in cam.seen: dup += 1; continue
cam.seen.add(key)
pos = bisect_right(cam.ts, e["timestamp"])
cam.ts.insert(pos, e["timestamp"]); cam.entries.insert(pos, e)
accepted += 1
return jsonify(accepted=accepted, duplicates=dup), 201
@app.get("/cameras/<cid>/logs")
def read(cid):
cam = cameras.get(cid)
if cam is None: return jsonify(error="unknown camera"), 404
try:
start = int(request.args.get("start", 0))
end = int(request.args["end"]) if "end" in request.args else None
limit = min(int(request.args.get("limit", 100)), MAX_LIMIT)
except ValueError:
return jsonify(error="start, end, limit must be integers"), 400
sev = request.args.get("severity")
if sev is not None and sev not in SEVERITIES: return jsonify(error="invalid severity"), 400
if limit <= 0 or (end is not None and end < start):
return jsonify(error="invalid range or limit"), 400
with cam.lock:
lo = bisect_left(cam.ts, start)
hi = len(cam.ts) if end is None else bisect_left(cam.ts, end)
out = []
for e in cam.entries[lo:hi]:
if sev is None or e["severity"] == sev:
out.append(e)
if len(out) == limit: break
return jsonify(entries=out), 200
Complexity
- Push: O(log n) search plus O(1) amortized append for in-order data, O(n) worst case for late entries.
- Range read: O(log n + k).
- Memory: O(total entries) plus the dedupe set.
Tests to include
- Push then read returns the same entries, sorted by timestamp.
- Out-of-order pushes still read back sorted; equal timestamps keep arrival order.
- Range boundaries:
startinclusive,endexclusive; empty range returns[]with 200. 400for bad JSON, missing fields, bad severity, non-integer timestamp,end < start.404for reading an unknown camera.- Duplicate push is not double-stored.
- Concurrency: spawn many threads pushing to the same camera and assert the final count and sorted order.
Trade-offs and common mistakes
- Wrong status codes: returning 200 for everything, or 500 on bad input. Validation failures are 4xx.
- Partial batch writes: decide all-or-nothing versus per-item results, and document it.
- Unbounded responses: always cap
limit; add cursor pagination (the last timestamp plus an offset among equal timestamps) for large ranges. - Sorting on every read instead of keeping data ordered.
- Locking the whole server around JSON serialization, which hurts throughput.
- Treating
boolasintin Python timestamp validation. - Ambiguous time semantics: state units, time zone (use UTC), and boundary inclusivity.
Follow-ups to be ready for
- Persistence: append-only file or SQLite with an index on
(camera_id, timestamp). - Retention: drop entries older than N days with a background sweep.
- Auth: per-camera API keys for writes, scoped tokens for reads.
- Scale-out: shard by camera id, put a queue in front of writes, and move to a time-series store.
- Relaying user commands to cameras: a separate
POST /cameras/{id}/commandswith asynchronous status, since cameras may be offline.