StackMoth/Work/Courts

Flagship · Booking, payments & IoT · Colombo

Courts that can’t be double-booked. Lights that only burn when they should.

A booking and payments platform running three live sports venues — wired to Raspberry Pi floodlight control at two of them.

3 Live venues
1,558+ Users
342 + 116 Automated tests
Live since 2024 In daily operation

01 / Database invariants

Never sell the same floor twice.

Half-court, full-court and dual-zone gym claims overlap physically. Try booking both for the same slot.

REFUSED · 23505 → HTTP 400

Court open for 19:00. Book half court A, then try an overlapping full court.

LAYER 01

pg_advisory_xact_lock

Serialises colliding booking transactions inside PostgreSQL without Redis or an external lock service.

LAYER 02

Two partial unique indexes

Half-court and full-court exclusion enforced as a database invariant, even if application code is bypassed.

LAYER 03

Clean 400 at the boundary

Translates a PostgreSQL 23505 unique violation into a clear HTTP 400 response.

02 / Multi-merchant payments

Money lands in the right company.

Webhooks are a hint. The gateway re-query is the truth.

CUSTOMER Card checkout DIALOG GENIE IPG gateway VERIFY Server re-query HMAC-SHA256 · 5m window VENUE slug router MERCHANT A MERCHANT B MERCHANT C

03 / Incident subsystem

When payments go weird.

Decoupled booking lifecycle & payment outcome
Booking lifecycle: PENDING ──► HELD ──► CONFIRMED └──(past payable_until)──► EXPIRED / CANCELLED Payment outcome: pending ──(gateway verify)──► success └──► received_under_review
46 → 0

Historical transactions reconciled to zero unaccounted charges.

04 / Daylight gating & inrush

Lights on only when booked — and dark.

Dual battery Zigbee lux sensors · Fails closed on stale readings

15 min fresh 20 min warn 30 min stale → off

During daytime bookings, natural daylight clears the threshold and suppresses floodlights. When darkness arrives, banks strike in sequence to prevent inrush spikes.

T-15
Bank 1 strike
T-10
Bank 2 strike
T
Full court lit

05 / Positive confirmation

A success that wasn’t.

courtres.log — two lines from the same second
08:25:35.954 Full Court light confirmed off 08:25:36 genOnOff.off ... timed out after 10000ms
+0.85 s — reported off before the radio gave up trying

A light is off when the light says it’s off.

12 s confirm > 10 s ZCL timeout Bridge logging topic monitored Zigbee Ch 11 vs Wi-Fi Ch 9

06 / Proven abstraction

Swapped the whole radio. Main app diff: 0 lines.

Before July 2026

Wi-Fi relays

Intermittent drops

→ 0 lines changed in app.py →
July 2026 → present

Zigbee + zigbee2mqtt

0 unrecovered failures since

Deep dive · Part A

Reservation & payment platform notes

01Facts & production footprint
Client
A Colombo sports facility operator
Period
Dec 2024 to present
Scale
~49,800 lines, 235 commits
In production
3 active venues (incl. dual-zone gym), 1,558+ users
Stack
Express 4.21, TypeScript, Next.js 15, React 18, raw PostgreSQL (pg pool, no ORM)
Payments
Dialog Genie IPG, multi-merchant routing
Tests
342 backend tests
Access
Live and in daily use. Not linked publicly.
02The problem is physical & three-layer double-booking defence

A court sold twice is not a scheduling annoyance. It is two paying customers standing on the same floor at the same time, and a front desk with no good answer. Half-court, full-court and dual-zone gym reservations overlap, so the rule is “no overlapping claim on the same physical space”.

  • Transaction-scoped advisory lock: pg_advisory_xact_lock serialises requests that could collide, with no Redis or external lock service.
  • Two overlapping partial unique indexes: half-court and full-court exclusion encoded as a database invariant.
  • Clean failure at the boundary: 23505 unique violation translated into HTTP 400.
03Multi-merchant settlement, July 2026 race conditions & SQL tests

The three venues operate across distinct merchant accounts. Card payments run through Dialog Genie with merchant credentials selected per venue slug. The server re-queries the payment provider for authoritative state; webhooks are verified with HMAC-SHA256, a five-minute replay window and timingSafeEqual, and treated only as a hint to check.

After three real-world gateway edge cases in July 2026 (no void API, unreliable webhooks, silent expiry fallbacks), an idempotent payment_incidents ledger, classification taxonomy, received_under_review outcome and cancellation_source provenance column were added, reconciling 46 historical transactions down to zero unaccounted charges.

A single shared SQL fragment (payable_until) defines the payment deadline for both UI countdown and server expiry. 342 backend tests include assertions on generated SQL text so a refactor cannot quietly drop an advisory lock or partial index.

Deep dive · Part B

Floodlight control & IoT notes

04Hardware topology & facts
Period
Nov 2024 to present
Scale
5,500 lines of Python, 33 commits
Deployment
Dual Raspberry Pi nodes over Tailscale, unattended at two sports venues
Hardware
Raspberry Pi 3B, Sonoff EFR32MG21 (ZBDongle-E), relays, dual battery lux sensors
Transport
Zigbee via zigbee2mqtt and loopback-only mosquitto
Tests
116 tests across 8 suites
Booking API ──► Raspberry Pi (Tailscale + systemd) │ ▼ mosquitto (127.0.0.1 only) │ ▼ zigbee2mqtt + Sonoff EFR32MG21 (Ch 11) ├──► Floodlight relays (positive state feedback) └──► Dual battery Zigbee lux sensors
05Positive confirmation, lux gate & site engineering

Command acknowledgement was removed as a success signal after logs revealed the app reported success 0.85 s before a 10 s ZCL timeout. The controller now waits up to 12 seconds for the device to republish its own strictly newer state, and subscribes to the zigbee2mqtt bridge logging topic to surface silent radio faults.

Dual battery Zigbee lux sensors gate daytime floodlights with 15/20/30-minute freshness tiers and per-sensor calibration, failing closed (allowed: false) if no fresh reading is available.

  • Zigbee on channel 11 against venue Wi-Fi on channel 9.
  • Loopback-only MQTT with remote access over Cloudflare Tunnels and Tailscale (no staff VPN needed).
  • Inrush staggering at T-15, T-10 and T.
  • Multi-process-safe rotating logs with file locking and atomic status snapshots via os.replace.

AI-assisted, human-accountable. AI tools contributed significantly to the implementation described here. The specification, the review of every change, the production operation and the accountability are mine.

Next flagship

SILK Residencies & Mall