Review a Seat-Booking Backend for Security and Data Integrity
System DesignModel answerLast updated
Review a small Python and SQL ticket-booking service by reading only, and write at least ten fix-oriented comments across security, concurrency, schema, reliability and maintainability.
You are reviewing a pull request for a small ticket-booking backend. It is written in Python with PostgreSQL. You cannot run it, so your review has to come from reading the code alone.
# config.py
import psycopg2
PG_PASS = "hunter2-prod"
db = psycopg2.connect(host="db.prod.internal", user="postgres", password=PG_PASS)
# booking.py
from datetime import datetime
from config import db
def book_seat(customer, event_id, seats):
c = db.cursor()
c.execute("SELECT seats_left FROM events WHERE id = " + str(event_id))
left = c.fetchone()[0]
if left >= seats:
c.execute("INSERT INTO bookings VALUES ('%s', %s, %s, '%s')"
% (customer, event_id, seats, datetime.now()))
c.execute("UPDATE events SET seats_left = %d WHERE id = %s"
% (left - seats, event_id))
db.commit()
return "ok"
def bookings_for(customer):
c = db.cursor()
c.execute(f"SELECT * FROM bookings WHERE customer = '{customer}'")
return c.fetchall()
CREATE TABLE events (id INT, title TEXT, seats_left INT, ticket_price REAL);
CREATE TABLE bookings (customer TEXT, event_id INT, seats INT, booked_at VARCHAR(40));
Your task
- Write at least 10 review comments, each in a different area. Cover, for example, security, correctness, data modeling, concurrency, reliability, performance, testing and maintainability.
- For each comment, state where the problem is, why it matters, and a concrete fix. The fix can be a code change, a schema change, a configuration change, or a test or monitoring addition.
- Rank the comments by severity (blocker, major, minor) so the author knows what to fix first.
- Briefly show how the core booking function would look after your fixes.
Hints
Hint 1
Go through the code in a fixed order: security first, then correctness, then data integrity and concurrency, then schema, then operations and tests. This keeps you from missing whole categories.
Hint 2
Ask what happens when two requests call book_seat at the same moment, and what happens when the second SQL statement fails after the first succeeded.
Hint 3
Look at the schema as if the application code did not exist. Which rows could be inserted that make no sense, and what would the database do to stop them?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A strong review has three qualities: breadth (distinct areas, not ten variations of one bug), prioritization (blockers before nits), and actionable fixes (a diff or a specific change, not "make this safer"). I use a fixed pass order: security, correctness, integrity and concurrency, schema, operations, tests and maintainability. Each comment gets a severity, a location, the impact, and the fix.
Review comments
1. [Blocker] Security: hard-coded credential (config.py)
The production password is committed to the repo. It is visible to everyone with access and stays in git history even after deletion.
Fix: Load it from an environment variable or a secrets manager. Rotate the leaked password immediately. Add a secret scanner (gitleaks or detect-secrets) to pre-commit and CI.
2. [Blocker] Security: SQL injection (booking.py, all three queries)
Concatenation, % formatting and f-strings put raw input into SQL. A customer value such as x' OR '1'='1 in bookings_for returns every booking. A crafted value in book_seat can modify or destroy data.
Fix: Use bound parameters: c.execute("SELECT ... WHERE customer = %s", (customer,)). Add a lint rule (for example Bandit) that flags string-built SQL.
3. [Blocker] Concurrency: check-then-act race on seats_left
Two requests can both read seats_left = 2, both pass the check, and both book 2 seats. The UPDATE then writes an absolute value computed from a stale read, so one decrement is lost and the event is oversold.
Fix: Make the decrement a single conditional statement:
UPDATE events SET seats_left = seats_left - %s WHERE id = %s AND seats_left >= %s RETURNING seats_left.
Insert the booking only if a row was returned. SELECT ... FOR UPDATE in the same transaction is an acceptable alternative.
4. [Blocker] Transactions: no atomicity and no rollback
If the UPDATE fails after the INSERT, the connection stays in an aborted transaction and the next call on it fails. There is no rollback(), so the booking row and the seat count can disagree.
Fix: Run the unit of work inside with conn: (commit on success, rollback on exception), or use an explicit try/except with rollback().
5. [Major] Correctness: crash on a missing event and a misleading return value
fetchone()returnsNonefor an unknown event, so[0]raisesTypeError.- The function returns
"ok"even when seats were insufficient, so callers believe the booking succeeded. - Nothing validates
seats > 0. A negative value would increase availability.
Fix: Raise domain exceptions (EventNotFound, SoldOut) or return the new booking id. Validate input at the boundary.
6. [Major] Schema: no keys or referential integrity
events.id is not unique and bookings has no identifier, so duplicates and orphan rows are possible.
Fix: Add id BIGSERIAL PRIMARY KEY to both tables and event_id BIGINT NOT NULL REFERENCES events(id). Reference a real customers table instead of a free-text name.
7. [Major] Schema: wrong types
ticket_price REALis a binary float and rounds money incorrectly. UseNUMERIC(10,2)or integer cents.booked_at VARCHAR(40)holds a local, timezone-naive string that cannot be reliably sorted or range-queried. UseTIMESTAMPTZ NOT NULL DEFAULT now().customer TEXTas an identifier invites typos and case mismatches.
8. [Major] Schema: invariants live only in application code
Any other code path or manual fix can break them.
Fix: Add CHECK (seats_left >= 0), CHECK (seats > 0) and NOT NULL on required columns. The first check is the last line of defense against overselling.
9. [Major] Reliability: no idempotency
A client that retries after a timeout creates a duplicate booking and consumes more seats.
Fix: Accept an idempotency key, add UNIQUE (customer_id, idempotency_key), and use INSERT ... ON CONFLICT DO NOTHING RETURNING id. On conflict, return the existing booking.
10. [Major] Concurrency and operations: one global connection
A module-level connection shared across threads means one request's failure poisons the others, and the process never reconnects after a database restart.
Fix: Use a connection pool (ThreadedConnectionPool or SQLAlchemy). Take a connection per unit of work, release it in finally, and set connect and statement timeouts.
11. [Major] Security: excessive privileges
Connecting as postgres (superuser) turns any injection bug into total compromise.
Fix: Create an application role with only SELECT, INSERT and UPDATE on the tables it needs. Run migrations with a separate role.
12. [Minor] Maintainability: SELECT * and an INSERT without a column list
Adding or reordering columns silently breaks the code or returns unexpected data.
Fix: Name columns explicitly. Manage schema changes with migrations (Alembic or Flyway) instead of ad-hoc DDL.
13. [Minor] Performance: missing indexes
bookings_for scans the whole table, and bookings has no index on event_id.
Fix: Add INDEX ON bookings (customer_id, booked_at DESC) and INDEX ON bookings (event_id). Postgres does not index foreign keys automatically.
14. [Minor] Observability There is no logging or metrics, so oversell attempts and failures are invisible. Fix: Use structured logs with the booking id and no PII or secrets. Add counters for successful bookings and sold-out rejections, and alert on database error rates.
15. [Major] Testing Mock-based unit tests cannot catch the race or the injection. Fix: Add integration tests against a real Postgres (for example testcontainers):
- unknown event
- insufficient seats
- injection strings stored as literal text
- 50 concurrent requests for 10 remaining seats, asserting exactly 10 succeed and
seats_leftends at 0
Sketch of the fixed core
CREATE TABLE events (
id BIGSERIAL PRIMARY KEY,
title TEXT NOT NULL,
seats_left INT NOT NULL CHECK (seats_left >= 0),
ticket_price NUMERIC(10,2) NOT NULL CHECK (ticket_price >= 0)
);
CREATE TABLE bookings (
id BIGSERIAL PRIMARY KEY,
customer_id BIGINT NOT NULL REFERENCES customers(id),
event_id BIGINT NOT NULL REFERENCES events(id),
seats INT NOT NULL CHECK (seats > 0),
idempotency_key UUID NOT NULL,
booked_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (customer_id, idempotency_key)
);
def book_seat(pool, customer_id, event_id, seats, key):
if seats <= 0:
raise ValueError("seats must be positive")
conn = pool.getconn()
try:
with conn, conn.cursor() as c:
c.execute(
"UPDATE events SET seats_left = seats_left - %s "
"WHERE id = %s AND seats_left >= %s RETURNING id",
(seats, event_id, seats))
if c.fetchone() is None:
raise SoldOutOrMissing(event_id)
c.execute(
"INSERT INTO bookings (customer_id, event_id, seats, idempotency_key) "
"VALUES (%s, %s, %s, %s) RETURNING id",
(customer_id, event_id, seats, key))
return c.fetchone()[0]
finally:
pool.putconn(conn)
A real version would also handle the idempotency conflict. If the key already exists, the seat decrement must roll back and the existing booking id must be returned.
Common mistakes
- Listing five variations of "SQL injection" instead of covering distinct areas.
- Saying "use a transaction" without noticing that the read-check-write race persists unless the update is conditional or the row is locked.
- Removing the password from the code but not rotating it.
- Offering vague advice with no concrete diff, schema change or test.