Code Review Expert

Performs a rigorous senior-level code review covering correctness, design, performance, and security with prioritized, actionable fixes.

// prompt
You are a **principal software engineer** performing a rigorous, senior-level code review. Be direct, specific, and constructive — flag real problems, explain *why* they matter, and show exactly how to fix them. ## Context - **Language / Stack:** {{programming_language}} / {{framework_or_stack}} - **What the code does:** {{project_context}} - **Primary review focus:** {{review_focus}} ## Code to review ``` {{code_to_review}} ``` ## How to review Evaluate the code methodically across these dimensions: 1. **Correctness & edge cases** — logic errors, off-by-one, null/empty handling, race conditions, unhandled failures. 2. **Readability & maintainability** — naming, structure, function size, duplication, comment/documentation quality. 3. **Design & SOLID principles** — single responsibility, sensible abstractions, coupling, testability. 4. **Performance** — algorithmic complexity, redundant work, memory use, obvious bottlenecks. 5. **Security** — input validation, injection risks, secret handling, unsafe dependencies. 6. **Testing** — coverage gaps and missing cases worth adding. ## Deliver your review in this format **Summary** — 2-3 sentences on overall quality and the most important takeaway. **Issues** — ordered by severity. For each: - **Severity:** Critical / High / Medium / Low - **Location:** file, function, or line reference - **Problem:** what is wrong and why it matters - **Fix:** concrete suggestion, with a short corrected code snippet where helpful **Strengths** — what the code does well and should be preserved. **Recommendations** — prioritized refactors and best-practice improvements, framed as actionable next steps. Base every comment on the code shown — do not invent context. If something is ambiguous, state your assumption. Keep feedback respectful and focused on the code, not the author.
Fill in the variables

Example run

Generated by Claude Opus 5.5 on November 25, 2026

Inputs used

Programming language
Python
Framework or stack
FastAPI + SQLAlchemy (async, PostgreSQL) on Python 3.11
Project context
This is part of "Severtrans Shop", a small B2B e-commerce backend used by a logistics parts supplier. The module below implements the coupon redemption flow: a customer submits a coupon code at checkout, the service looks it up, validates it (expiry, usage limit, minimum order value), applies the discount to the current cart total, and records the redemption. It's called from the `/checkout/apply-coupon` endpoint and is hit roughly 2,000 times/day, with spikes during seasonal sales (e.g. the upcoming Black Friday weekend, Nov 27-30, 2026) when the same popular codes (like "WINTER2026") get submitted by many customers within seconds of each other. The team has noticed that during last year's Black Friday sale, a 20%-off code with a cap of 100 uses ended up being redeemed 143 times, and support had to manually reverse the extra discounts. This module was written quickly before that sale and hasn't been touched since.
Review focus
Focus primarily on correctness under concurrency (we strongly suspect a race condition in the usage-limit check-and-increment logic that caused the overselling bug last Black Friday) and on security (the code string is interpolated into a raw SQL query in one place, which worries me). Secondary focus: error handling for malformed/missing coupon codes, and whether the discount math correctly handles edge cases like zero-value carts or codes with both percentage and fixed-amount discounts. Please also flag any obvious testing gaps, but performance and pure style nitpicks are lower priority for this review.
Code to review
from fastapi import APIRouter, Depends, HTTPException from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession from decimal import Decimal from datetime import datetime from app.db import get_session from app.models import Coupon, Redemption router = APIRouter() @router.post("/checkout/apply-coupon") async def apply_coupon(payload: dict, session: AsyncSession = Depends(get_session)): code = payload.get("code") cart_total = payload.get("cart_total") user_id = payload.get("user_id") # Look up coupon by raw code string query = f"SELECT * FROM coupons WHERE code = '{code}' AND active = true" result = await session.execute(text(query)) row = result.fetchone() if not row: return {"error": "Coupon not found"} coupon = row # Check expiry if coupon.expires_at < datetime.utcnow(): return {"error": "Coupon expired"} # Check minimum order value if cart_total < coupon.min_order_value: return {"error": "Order total too low for this coupon"} # Check usage limit used_count_result = await session.execute( text(f"SELECT COUNT(*) FROM redemptions WHERE coupon_id = {coupon.id}") ) used_count = used_count_result.scalar() if used_count >= coupon.max_uses: return {"error": "Coupon usage limit reached"} # Apply discount if coupon.discount_type == "percent": discount = cart_total * (coupon.discount_value / Decimal(100)) else: discount = coupon.discount_value new_total = cart_total - discount # Record redemption redemption = Redemption( coupon_id=coupon.id, user_id=user_id, amount_discounted=discount, created_at=datetime.utcnow(), ) session.add(redemption) await session.commit() return { "original_total": cart_total, "discount_applied": discount, "new_total": new_total, "coupon_code": coupon.code, }

Code Review: apply_coupon (Severtrans Shop)

Summary

This handler has two critical defects that need fixing before the Black Friday sale on Nov 27. A SQL injection lets any caller read the database or invent a coupon. A check-then-insert race on the usage limit fully explains last year's 143-of-100 overselling. Beyond those, the handler trusts client-supplied cart_total and user_id, crashes on common inputs, and can return negative totals. The fixes are small, and a safe hotfix needs no schema migration, so it can ship this week.


Issues

1. SQL injection in coupon lookup

  • Severity: Critical

  • Location: apply_coupon, query = f"SELECT * FROM coupons WHERE code = '{code}' AND active = true"

  • Problem: code comes straight from the request body and is pasted into SQL. Three concrete attacks:

    • Free coupon: code = "' OR '1'='1" matches every active coupon, and fetchone() returns whichever comes first.
    • Invented coupon: code = "x' UNION SELECT <crafted columns> --" returns a fake row. The attacker controls discount_value, max_uses, expires_at, and min_order_value. The discount is then computed from attacker data, and a Redemption is written against an attacker-chosen coupon_id.
    • Data theft: The response differs between "not found" and other outcomes. That gives a boolean oracle for blind injection, which can extract any table the DB role can read: customers, orders, credentials.

    The second query, f"... WHERE coupon_id = {coupon.id}", is less exploitable because the value comes from the DB. But after a UNION injection, coupon.id is attacker-controlled, so that query is injectable too.

    payload.get("code") can also be None, a list, or a number. The f-string turns any of them into SQL (for example code = 'None').

  • Fix: Never build SQL from strings. Use the ORM model you already import, or bound parameters:

    stmt = select(Coupon).where(Coupon.code == code, Coupon.active.is_(True))
    coupon = (await session.execute(stmt)).scalar_one_or_none()
    
    # or, if you must use text():
    await session.execute(
        text("SELECT ... FROM coupons WHERE code = :code AND active"), {"code": code}
    )
    

    As defense in depth, make sure the app's DB role has only the privileges it needs.

2. Race condition in the usage-limit check (the Black Friday overselling bug)

  • Severity: Critical

  • Location: apply_coupon, from the SELECT COUNT(*) through session.commit()

  • Problem: This is a classic time-of-check/time-of-use race. PostgreSQL's default READ COMMITTED isolation does not stop two transactions from interleaving like this:

    t Request A Request B
    1 COUNT(*) → 99
    2 COUNT(*) → 99
    3 99 < 100 ✓, INSERT 99 < 100 ✓, INSERT
    4 COMMIT → 100 COMMIT → 101

    Nothing in the code or the schema shown serializes these requests. With N concurrent submissions of WINTER2026 near the cap, up to N−1 extra redemptions get through. That matches 143/100.

  • Fix: Pick one of the two options below. Both make the check and the claim atomic per coupon.

    Option A: hotfix, no migration (ship before Nov 27). Lock the coupon row for the length of the transaction:

    coupon = (await session.execute(
        select(Coupon)
        .where(Coupon.code == code, Coupon.active.is_(True))
        .with_for_update()
    )).scalar_one_or_none()
    # ...validation...
    used = (await session.execute(
        select(func.count()).select_from(Redemption).where(Redemption.coupon_id == coupon.id)
    )).scalar_one()
    if coupon.max_uses is not None and used >= coupon.max_uses:
        raise HTTPException(409, "Coupon usage limit reached")
    session.add(Redemption(...))
    await session.commit()   # lock released here
    

    This works for three reasons:

    • The row lock is held until commit, so concurrent requests for the same code queue up behind it.
    • Under READ COMMITTED, each statement takes a fresh snapshot, so the COUNT run after acquiring the lock sees every previously committed redemption.
    • Requests for different coupons don't block each other.

    At your volume, serializing a short transaction on a hot code is fine.

    Option B: durable fix. Add a used_count column, backfilled from redemptions. Claim a use with a single conditional UPDATE, and add a DB constraint as a backstop:

    ALTER TABLE coupons ADD COLUMN used_count int NOT NULL DEFAULT 0;
    UPDATE coupons c SET used_count = (SELECT count(*) FROM redemptions r WHERE r.coupon_id = c.id);
    ALTER TABLE coupons ADD CONSTRAINT used_within_limit
        CHECK (max_uses IS NULL OR used_count <= max_uses);
    
    claimed = await session.execute(
        update(Coupon)
        .where(
            Coupon.id == coupon.id,
            or_(Coupon.max_uses.is_(None), Coupon.used_count < Coupon.max_uses),
        )
        .values(used_count=Coupon.used_count + 1)
        .returning(Coupon.id)
    )
    if claimed.scalar_one_or_none() is None:
        raise HTTPException(409, "Coupon usage limit reached")
    session.add(Redemption(...))
    await session.commit()  # increment and redemption commit or roll back together
    

    This also removes the per-request COUNT(*). The CHECK constraint means a future code path that forgets the guard will fail loudly instead of overselling.

    If coupons are meant to be one per customer (an assumption, since the code doesn't say), also add UNIQUE (coupon_id, user_id) on redemptions. Today a single user can redeem a code 100 times.

3. Client controls cart_total and user_id

  • Severity: High
  • Location: cart_total = payload.get("cart_total"), user_id = payload.get("user_id")
  • Problem: I'm assuming there is no upstream authentication or cart validation, because none is visible here. Under that assumption:
    • A client can send cart_total = 1_000_000 to pass min_order_value, or to inflate a percent discount that is then recorded in amount_discounted.
    • If any downstream step trusts the returned new_total, this becomes direct price tampering.
    • user_id from the body lets anyone file redemptions under another customer's account. That is impersonation, and it would also defeat any per-user limit.
  • Fix: Derive the user from the authenticated principal, e.g. user = Depends(get_current_user) (a placeholder for your auth dependency). Compute the cart total server-side from the persisted cart. If that can't land before the sale, at least re-validate the total at order placement and treat this endpoint's numbers as a preview only.

4. No input validation; common inputs cause 500s

  • Severity: High
  • Location: payload: dict; the comparison and arithmetic on cart_total
  • Problem:
    • Missing cart_total: None < Decimal raises TypeError, which becomes a 500.
    • Decimal amounts like 99.99: JSON numbers with a fractional part are parsed as Python float, and float * Decimal raises TypeError. So every percent coupon crashes on a non-integer cart total. Integer totals happen to work, which is probably why this slipped through.
    • String values like "100": str < Decimal raises TypeError.
    • Negative totals are accepted.
    • Missing or non-string code goes straight into the query (see #1).
  • Fix: Use a Pydantic model so FastAPI rejects bad input with a 422 before your code runs:
    from typing import Annotated
    from pydantic import BaseModel, Field, StringConstraints
    
    CouponCode = Annotated[str, StringConstraints(
        strip_whitespace=True, to_upper=True, min_length=1, max_length=64,
        pattern=r"^[A-Z0-9_-]+$",
    )]
    
    class ApplyCouponRequest(BaseModel):
        code: CouponCode
        cart_total: Decimal = Field(ge=0, max_digits=12, decimal_places=2)  # interim, see #3
    
    Pydantic parses "99.99" and 99.99 into Decimal correctly. Normalizing case and whitespace also fixes " winter2026" failing to match WINTER2026, assuming codes are stored uppercase.

5. Discount math: negative totals, no rounding, unknown types silently become "fixed"

  • Severity: High

  • Location: the # Apply discount block

  • Problem:

    • Fixed discount larger than the cart: €50 off a €30 cart gives new_total = -20.
    • Bad percent values: discount_value > 100 gives a negative total. A negative discount_value increases the price.
    • No quantization: 33.33 * 0.15 = 4.9995. The response and amount_discounted carry sub-cent values, and original - discount may not reconcile with what's eventually charged.
    • Unknown types: The else branch treats every non-"percent" value as fixed, including None, typos, and a hypothetical "percent_plus_fixed". On your "both percentage and fixed" question: the code shown supports only one type per coupon, and a combined type would be silently misapplied as fixed.
    • Zero-value carts: If min_order_value is 0, a €0 cart passes. It gets a €0 discount (percent) or a negative total (fixed), and still burns one of the limited uses.
  • Fix: Extract a pure, testable function. Reject unknown types, cap the discount at the cart total, and quantize:

    from decimal import ROUND_HALF_UP
    CENT = Decimal("0.01")
    
    def compute_discount(cart_total: Decimal, discount_type: str, value: Decimal) -> Decimal:
        if cart_total <= 0:
            return Decimal("0.00")
        if discount_type == "percent":
            if not (Decimal(0) < value <= Decimal(100)):
                raise ValueError(f"Invalid percent value {value}")
            raw = cart_total * value / Decimal(100)
        elif discount_type == "fixed":
            if value <= 0:
                raise ValueError(f"Invalid fixed value {value}")
            raw = value
        else:
            raise ValueError(f"Unknown discount_type {discount_type!r}")
        return min(raw, cart_total).quantize(CENT, rounding=ROUND_HALF_UP)
    

    In the handler, reject the request (422) when the discount is 0 so no use is consumed. If you ever need combined discounts, add an explicit type with a documented order (for example, percent first, then fixed, capped at the total) rather than overloading else. The rounding mode is a business decision; confirm it with finance.

    Also add DB CHECK constraints on discount_type and discount_value so bad coupon rows can't be created in the first place.

6. Errors returned as HTTP 200

  • Severity: Medium

  • Location: every return {"error": ...}

  • Problem: Failures come back as 200 OK. Any client that checks the status code, or reads new_total without checking for error, treats a rejected coupon as success. HTTPException is imported but never used.

  • Fix: Raise with appropriate status codes:

    Case Status
    Coupon not found 404
    Expired 410 or 422
    Below minimum order 422
    Limit reached 409

7. Timezone and NULL handling in validation

  • Severity: Medium
  • Location: coupon.expires_at < datetime.utcnow(), cart_total < coupon.min_order_value, used_count >= coupon.max_uses
  • Problem:
    • Timezone crash: datetime.utcnow() is naive (and deprecated since 3.12). If expires_at is timestamptz, asyncpg returns an aware datetime, and naive-vs-aware comparison raises TypeError on every request. If the column is timestamp without time zone, the comparison works but depends on everyone storing UTC.
    • NULL crashes: A NULL expires_at, min_order_value, or max_uses also raises TypeError. I'm assuming NULL means "no limit", which is a common convention.
  • Fix: Do the expiry check in SQL against the DB clock, and guard nullable fields explicitly:
    .where(or_(Coupon.expires_at.is_(None), Coupon.expires_at > func.now()))
    
    Use datetime.now(timezone.utc) for created_at, or better, a server default of now().

8. Redemption is recorded at "apply" time, not at order placement

  • Severity: Medium (a design concern; confirm intent)
  • Location: session.add(redemption) inside apply-coupon
  • Problem: I'm assuming "apply" happens before the order is placed, as the endpoint name suggests. Then:
    • Every apply burns a use, including abandoned carts, page refreshes, and double-clicks.
    • During a rush, legitimate buyers will see "limit reached" while many of the 100 uses sit on abandoned carts.
    • There's no idempotency: applying twice records two redemptions.
  • Fix: Make apply a validation and preview step that writes nothing. Perform the atomic claim from #2 at order placement, in the same transaction that creates the order. If you need to hold a spot, use a reservation with a TTL. Wherever consumption ends up, it must use the atomic claim.

9. No transaction error handling

  • Severity: Medium
  • Location: await session.commit()
  • Problem: Once you add the unique and check constraints, commits can raise IntegrityError. Unhandled, that becomes a 500. Whether the session is rolled back depends on get_session, which isn't shown.
  • Fix: Catch IntegrityError, roll back, and map it to 409. Confirm that get_session rolls back on exception.

10. Coupon-code enumeration

  • Severity: Low–Medium
  • Location: the endpoint as a whole
  • Problem: There's no rate limiting. The distinct "not found" and "expired" messages let attackers brute-force valid or once-valid codes, and short codes like WINTER2026 are guessable.
  • Fix: Rate-limit per user and per IP. Consider returning one generic message for not-found and expired, while logging the real reason server-side.

11. Decimal precision lost in the JSON response

  • Severity: Low
  • Location: the return dict
  • Problem: FastAPI's encoder converts Decimal to float, so money values lose exactness on the wire.
  • Fix: Use a response model that serializes amounts as strings, or as integer cents.

12. Unused imports, raw SELECT *, logic in the route

  • Severity: Low
  • Location: imports; the handler body
  • Problem:
    • Coupon and HTTPException are imported but unused.
    • SELECT * couples the code to column order and table shape.
    • All logic lives in the route handler, so none of it is unit-testable.
  • Fix: Separate the layers:
    • The route handles HTTP and auth.
    • A CouponService.redeem() handles the transaction and locking.
    • A pure compute_discount() handles the math.

Strengths

  • Uses Decimal for money rather than float, which is the right foundation.
  • Uses an async session via dependency injection, so swapping in a test session is easy.
  • The validation order (exists → not expired → meets minimum → under limit) is logical. Checking cheap conditions before the count query is sensible.
  • Records amount_discounted per redemption, which provides a good audit trail. It made last year's manual reversal possible.
  • An active flag gives ops a kill switch for a code.

Recommendations (prioritized)

Before Nov 27 (hotfix):

  1. Replace both f-string queries with ORM or bound parameters (#1).
  2. Add with_for_update() on the coupon lookup (#2, Option A).
  3. Add the Pydantic request model (#4) and the capped, quantized compute_discount (#5).
  4. Switch to HTTPException with proper status codes (#6). Coordinate with the frontend, since its error handling currently keys off a 200 + error field.
  5. Run the concurrency test below against a real Postgres instance before deploying.
  6. Preventive SQL: run a one-off query to detect current overruns, and run it again during the sale:
    SELECT c.code, c.max_uses, count(r.*) AS used
    FROM coupons c JOIN redemptions r ON r.coupon_id = c.id
    GROUP BY c.id HAVING count(r.*) > c.max_uses;
    

After the sale:

  1. Migrate to a used_count column with a CHECK constraint and atomic UPDATE ... RETURNING (#2, Option B).
  2. Add a UNIQUE (coupon_id, user_id) constraint if the policy is one use per customer.
  3. Move consumption to order placement and make apply side-effect-free (#8).
  4. Take user_id from auth and cart_total from the server-side cart (#3).
  5. Move expiry checks into SQL with now(), and handle NULL limits (#7).
  6. Add rate limiting (#10) and a typed response model (#11).

Testing gaps to close:

The most important test, against real Postgres (SQLite and mocks won't reproduce the race):

async def test_usage_limit_holds_under_concurrency(client, make_coupon):
    await make_coupon(code="RACE", max_uses=100)
    results = await asyncio.gather(*[
        client.post("/checkout/apply-coupon", json={"code": "RACE", "cart_total": "50.00"})
        for _ in range(300)
    ])
    assert sum(r.status_code == 200 for r in results) == 100
    assert await count_redemptions("RACE") == 100

Other cases to cover:

  • Injection: code="' OR '1'='1" and a UNION payload both return 404 or 422, never a discount.
  • Validation: missing, null, or non-string code; missing, string, negative, or float cart_total (99.99, which currently crashes percent coupons). All should return 422, never 500.
  • Boundaries:
    • cart_total == min_order_value (should pass).
    • used == max_uses - 1 (should pass) versus used == max_uses (should fail).
    • expires_at exactly now.
  • Math:
    • Fixed discount larger than the cart (capped, never negative).
    • Percent at 0, 100, and above 100.
    • Rounding (33.33 @ 15% → 5.00).
    • Zero cart (rejected, no use consumed).
    • Unknown discount_type (error, not treated as fixed).
  • NULL fields: expires_at, max_uses, and min_order_value, plus a timezone-aware expires_at.
  • Property test (Hypothesis): for any valid input, 0 <= discount <= cart_total and new_total + discount == cart_total.

Related prompts

Programming & Development

Professional Code Generator

Generates clean, well-documented, production-ready code from your requirements, following best practices in any language.

{} 6 vars
Programming & Development

SQL Query Optimizer

Diagnoses a slow SQL query and returns an optimized rewrite, index plan, and execution-plan reasoning.

{} 5 vars
Programming & Development

API Development Architect

Designs a production-ready RESTful API with OpenAPI spec, secure auth, validation, and scalable architecture.

{} 7 vars
Programming & Development

Advanced Debugging Assistant

Diagnoses bugs in your code, pinpoints root causes, and delivers fixed code with prevention tips.

{} 6 vars