Hardening a gift-card and voucher platform
Six months of client work on a live gift-card and voucher platform: pentest fixes, MySQL lock and deadlock fixes, exactly-once claims, a faster claim endpoint and a safer AWS release pipeline.
The platform
A client runs a multi-tenant gift-card and voucher platform. Businesses sell gift cards, vouchers and tickets through it, and staff redeem them at point-of-sale terminals or through an API. Underneath is a PHP 8.3 and Yii2 monolith on MySQL, with OpenSearch for search, a Nuxt buyer order form, and AWS ECS Fargate managed with Terraform.
From June to November 2026 I worked on its reliability, security and performance, more than 300 merged pull requests in all. The client and the platform stay unnamed here, so this page describes the kinds of problems and fixes, with numbers that can’t identify anyone.
Security fixes from a penetration test
A penetration test produced a long list of findings, and I worked through about 40 of them as separate fixes. All of these are fixed, and I’m describing classes of issue, not how to reproduce them.
- Several endpoints took a record ID and returned or changed it without checking that it belonged to the caller’s company. Each now scopes the lookup to the user’s own companies.
- Some endpoints and exports could be reached without logging in, or by any logged-in role. They now require login and, where needed, an admin role and a tenant match.
- A refused access check redirected the user but let the action keep running, so a request could still save data. Refusals now halt the request, and I searched the codebase for the same pattern instead of fixing one instance.
- Admin update actions accepted any posted field name as a column name, which opened a path to SQL injection. They now use per-action and per-role allow-lists.
- Table cells, search values in inline scripts and debug views now encode their output by default.
- Session cookies got the Secure and HttpOnly flags, logins lock out after repeated failures, a password change requires the current password, and users get an email when their password or email address changes.
- The app now sends HSTS, clickjacking protection and a report-only Content Security Policy.
- A dependency manifest and some ops files were readable from the web root and are now blocked or deleted. A payment client also put its own request options, including an API credential, into exception messages that reached the error tracker. I reproduced it, checked the retained logs (no credential had been recorded) and stopped the client from writing request options into errors.
Database locks and deadlocks
The most common production errors were MySQL lock-wait timeouts and deadlocks, and the victims were usually innocent single-row updates.
In one case, two unrelated updates failed three seconds apart. Neither was the cause. A cron job ran every five minutes with INSERT … SELECT … WHERE DATE(created_at) = CURDATE(). Wrapping the column in a function stopped MySQL from using the index, and INSERT … SELECT under REPEATABLE READ takes shared locks on every row it reads. So every five minutes the job locked the whole table to find one day’s rows.
| Query | Access | Rows read |
|---|---|---|
DATE(created_at) = CURDATE() |
full scan | 1,384,845 |
half-open range on created_at |
index range | 293 |
The fix was a half-open date range and READ COMMITTED for that statement, so its reads take no row locks:
WHERE created_at >= CURDATE()
AND created_at < CURDATE() + INTERVAL 1 DAY
The same pattern was behind a search-sync deadlock and a finance export that held locks for about three minutes while POS claims and payment callbacks timed out behind it.
The scale-out version of the bug showed up too. A nightly check flagged 94 cards with impossible balance history. Each had been expired twice, 11 seconds apart, because the expiry cron ran on every server and the duplicate guard only matched rows written in the same second. The fix takes a per-card advisory lock and re-reads the card’s status inside it, and it skips the card if it can’t get the lock. Two copies of another cron were also truncating each other’s shared staging table, which I replaced with a session-local temporary table.
Exactly-once claims
Some cards were claimed two or three times, 1 to 13 seconds apart, from POS double-taps, retries and concurrent submits. A card’s balance is its amount minus the sum of its claim log rows, so a duplicate row is a wrong balance.
A time window can’t tell a retry from a genuine second claim of the same amount. Only the identity of the operation can. The fix I wrote, reviewed but not merged yet, uses a client-supplied idempotency key (a per-form token, or an Idempotency-Key header on the API) with a database UNIQUE(item_id, idempotency_key) constraint. The balance change and the log insert run in one transaction. A duplicate key rolls back and replays the original result, and a different key goes through. It also disables submit buttons on click, so fewer duplicates reach the server at all. A payment callback got the same treatment: marking a card paid is now one atomic, once-only transition.
Performance
A claim endpoint averaged 1.3 to 2.1 seconds and kept tripping the latency alert. Traces showed 85% of the time was PHP CPU with no database spans, in two stalls of about 750 ms each. Model construction was doing quadratic work: a magic setter built a throwaway model just to read its column list, and each construction rebuilt every attribute label. One record load made 168,472 translation calls. Resolving labels once and reading columns from the schema cache removed the stall. I also added missing indexes on tables that hot endpoints were scanning.
The release pipeline on AWS
Several deploy failures were quiet ones:
- The deploy scripts asked the AWS CLI for the latest task definition with
--output text. The text formatter applies--queryto each page separately, and the family had reached exactly 100 revisions, so the scripts got two ARNs on two lines and failed with “Invalid revision number”. - Production was found pinned to a container image that registry retention had already deleted. The running tasks survived only because their hosts had the layers cached, and health checks stayed green. Now a scheduled check verifies that the image every service points at still exists.
- A Terraform apply deregistered the task definition a release was about to clone, the CLI waiter’s 10-minute cap reported a migration as failed while it was still running, and migrations were pinned to one availability zone that ran out of capacity. Each got its own fix: polling instead of the waiter, multi-AZ placement and surfacing ECS placement failures.
- The OpenTelemetry SDK exported spans before the response was sent. When the tracing backend accepted connections and never answered, each sampled request hung for about 40 seconds, enough to tie up every web worker and take down the order form while CPU sat idle. A 500 ms export timeout bounds it now, followed by a local collector sidecar. The same audit added connect and total timeouts to SDK, mail, shipping and search clients that had none.
What carried over
Most of these bugs came from assumptions that only held while the platform was small, like one server running each cron or one request at a time per card. The fixes that lasted moved the guarantee into the database or the pipeline instead of trusting timing. If you scale out a legacy app, audit every cron and every “once only” write for the assumption that only one copy runs.