KatInterview

Review a Seat-Booking Backend for Security and Data Integrity

System DesignModel answer
MediumModel answerSystem Designcode-reviewsql-injectiontransactions

Last 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

  1. Write at least 10 review comments, each in a different area. Cover, for example, security, correctness, data modeling, concurrency, reliability, performance, testing and maintainability.
  2. 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.
  3. Rank the comments by severity (blocker, major, minor) so the author knows what to fix first.
  4. 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?