Code Review Expert
Performs a rigorous senior-level code review covering correctness, design, performance, and security with prioritized, actionable fixes.
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:
codecomes straight from the request body and is pasted into SQL. Three concrete attacks:- Free coupon:
code = "' OR '1'='1"matches every active coupon, andfetchone()returns whichever comes first. - Invented coupon:
code = "x' UNION SELECT <crafted columns> --"returns a fake row. The attacker controlsdiscount_value,max_uses,expires_at, andmin_order_value. The discount is then computed from attacker data, and aRedemptionis written against an attacker-chosencoupon_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.idis attacker-controlled, so that query is injectable too.payload.get("code")can also beNone, a list, or a number. The f-string turns any of them into SQL (for examplecode = 'None'). - Free coupon:
-
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 theSELECT COUNT(*)throughsession.commit() -
Problem: This is a classic time-of-check/time-of-use race. PostgreSQL's default
READ COMMITTEDisolation does not stop two transactions from interleaving like this:t Request A Request B 1 COUNT(*)→ 992 COUNT(*)→ 993 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
WINTER2026near 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 hereThis 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 theCOUNTrun 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_countcolumn, backfilled fromredemptions. Claim a use with a single conditionalUPDATE, 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 togetherThis also removes the per-request
COUNT(*). TheCHECKconstraint 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)onredemptions. 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_000to passmin_order_value, or to inflate a percent discount that is then recorded inamount_discounted. - If any downstream step trusts the returned
new_total, this becomes direct price tampering. user_idfrom the body lets anyone file redemptions under another customer's account. That is impersonation, and it would also defeat any per-user limit.
- A client can send
- 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 oncart_total - Problem:
- Missing
cart_total:None < DecimalraisesTypeError, which becomes a 500. - Decimal amounts like
99.99: JSON numbers with a fractional part are parsed as Pythonfloat, andfloat * DecimalraisesTypeError. 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 < DecimalraisesTypeError. - Negative totals are accepted.
- Missing or non-string
codegoes straight into the query (see #1).
- Missing
- Fix: Use a Pydantic model so FastAPI rejects bad input with a 422 before your code runs:
Pydantic parsesfrom 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"99.99"and99.99intoDecimalcorrectly. Normalizing case and whitespace also fixes" winter2026"failing to matchWINTER2026, assuming codes are stored uppercase.
5. Discount math: negative totals, no rounding, unknown types silently become "fixed"
-
Severity: High
-
Location: the
# Apply discountblock -
Problem:
- Fixed discount larger than the cart: €50 off a €30 cart gives
new_total = -20. - Bad percent values:
discount_value > 100gives a negative total. A negativediscount_valueincreases the price. - No quantization:
33.33 * 0.15 = 4.9995. The response andamount_discountedcarry sub-cent values, andoriginal - discountmay not reconcile with what's eventually charged. - Unknown types: The
elsebranch treats every non-"percent"value as fixed, includingNone, 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_valueis 0, a €0 cart passes. It gets a €0 discount (percent) or a negative total (fixed), and still burns one of the limited uses.
- Fixed discount larger than the cart: €50 off a €30 cart gives
-
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
CHECKconstraints ondiscount_typeanddiscount_valueso 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 readsnew_totalwithout checking forerror, treats a rejected coupon as success.HTTPExceptionis 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). Ifexpires_atistimestamptz, asyncpg returns an aware datetime, and naive-vs-aware comparison raisesTypeErroron every request. If the column istimestamp without time zone, the comparison works but depends on everyone storing UTC. - NULL crashes: A NULL
expires_at,min_order_value, ormax_usesalso raisesTypeError. I'm assuming NULL means "no limit", which is a common convention.
- Timezone crash:
- Fix: Do the expiry check in SQL against the DB clock, and guard nullable fields explicitly:
Use.where(or_(Coupon.expires_at.is_(None), Coupon.expires_at > func.now()))datetime.now(timezone.utc)forcreated_at, or better, a server default ofnow().
8. Redemption is recorded at "apply" time, not at order placement
- Severity: Medium (a design concern; confirm intent)
- Location:
session.add(redemption)insideapply-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 onget_session, which isn't shown. - Fix: Catch
IntegrityError, roll back, and map it to 409. Confirm thatget_sessionrolls 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
WINTER2026are 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
Decimaltofloat, 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:
CouponandHTTPExceptionare 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
Decimalfor 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_discountedper redemption, which provides a good audit trail. It made last year's manual reversal possible. - An
activeflag gives ops a kill switch for a code.
Recommendations (prioritized)
Before Nov 27 (hotfix):
- Replace both f-string queries with ORM or bound parameters (#1).
- Add
with_for_update()on the coupon lookup (#2, Option A). - Add the Pydantic request model (#4) and the capped, quantized
compute_discount(#5). - Switch to
HTTPExceptionwith proper status codes (#6). Coordinate with the frontend, since its error handling currently keys off a 200 +errorfield. - Run the concurrency test below against a real Postgres instance before deploying.
- 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:
- Migrate to a
used_countcolumn with aCHECKconstraint and atomicUPDATE ... RETURNING(#2, Option B). - Add a
UNIQUE (coupon_id, user_id)constraint if the policy is one use per customer. - Move consumption to order placement and make apply side-effect-free (#8).
- Take
user_idfrom auth andcart_totalfrom the server-side cart (#3). - Move expiry checks into SQL with
now(), and handle NULL limits (#7). - 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 floatcart_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) versusused == max_uses(should fail).expires_atexactly 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, andmin_order_value, plus a timezone-awareexpires_at. - Property test (Hypothesis): for any valid input,
0 <= discount <= cart_totalandnew_total + discount == cart_total.
Related prompts
Professional Code Generator
Generates clean, well-documented, production-ready code from your requirements, following best practices in any language.
SQL Query Optimizer
Diagnoses a slow SQL query and returns an optimized rewrite, index plan, and execution-plan reasoning.
API Development Architect
Designs a production-ready RESTful API with OpenAPI spec, secure auth, validation, and scalable architecture.
Advanced Debugging Assistant
Diagnoses bugs in your code, pinpoints root causes, and delivers fixed code with prevention tips.