← Back to the interactive demo

PAYLAC / ENGINEERING CASE STUDY

PayLac: three engineering decisions

PayLac sends payment reminders on behalf of service firms, so a wrong email costs a client relationship, not just a support ticket. These are three decisions about making sure the right reminder goes to the right payer at most once — never twice, though a narrow timing window remains — with the evidence and the gaps I haven't closed yet.

Pre-pilot · not in production (as of 18 Nov 2026)

559 mocked tests passing (30 Jun 2026) · live verifiers with seeded test tenants (17–30 Jun 2026)

The product app is not deployed to production and has no real payers. Evidence here comes from mocked unit tests and recorded live verifier scripts run against the project's Supabase database with seeded test tenants.

  • Next.js
  • TypeScript
  • Supabase Postgres
  • Resend
  • Vitest

The approval path

Operator dashboardAPI: queue/add → reminder_queueinvoice/reopen-promise → invoicesAPI: reminders/approve → Resendstatus re-check before sendtenant scope on every user-facing writeResendAPI: webhooks/resend→ resend_email_eventsPayer pagetokenised link, no loginAPI: invoice/[token]/action→ invoices + invoice_actions+ reminder_queuePostgres also stores audit_logs
Nothing sends without an operator clicking approve. There is no scheduler.

DECISION 01

Tenant isolation

The problem

Many companies share one database. API routes use a server-side service-role client, which bypasses Postgres row-level security, so isolation can't be left to RLS.

What I chose

  • Dashboard routes take company_id only from the authenticated session, never from the request body.
  • Public payer routes have no session: the magic token is the credential, and company_id comes from the invoice that token matches.
  • The service-role client is created only after auth and input validation succeed.
  • User-facing writes are scoped by id + company_id, so a cross-tenant id matches zero rows and gets the same response as "not found".
  • Composite foreign keys (invoice_id, company_id) → invoices(id, company_id) on three tables make a cross-tenant row impossible at the database level, even if route code regressed.
  • Webhook events take company_id from the matched queue row, never from the payload.

Alternatives and why not

  • RLS policies with a user-scoped client for reads: every other read and write already goes through the service-role client with tenant scoping in code, so one RLS-based read would be the only boundary enforced a different way. I chose consistency for now.
  • Storing unmatched webhook events with null tenant columns: rejected in ADR-005 because it weakened the invariant that every stored row belongs to a known tenant. Unmatched events are logged and dropped.

Evidence

Trade-off

Isolation lives mainly in application code, backed by composite foreign keys on three tables. A few internal follow-up queries in the approve route filter on id only. They use ids that came from tenant-scoped reads, so they aren't exploitable as written, but they're inconsistent with the rest and are on the fix list.

DECISION 02

A payment promise arriving while a reminder is in flight

The problem

Between queueing and sending, the payer can click "I'll pay on [date]". A reminder that lands after that promise damages exactly the relationship PayLac exists to protect.

What I chose

two gates, because one isn't enough. The invoice can change after it has been queued.

  • Gate 1, payer side: the action sets the invoice to Promise or Disputed (both non-sendable), writes an append-only invoice_actions event, and moves any active queue rows to "skipped".
  • Gate 2, send side: approve claims the queue row with a compare-and-set (queued → sending), then re-reads the invoice's status and pause flag before calling Resend.
  • Only "draft" is sendable. It's an allow-list, so an unknown, future or null status fails closed.
  • Reopening a broken promise is one conditional write, Promise → draft. It never queues or sends; re-queueing goes through the normal queue path.

Alternatives and why not

  • A combined "reopen and re-queue" endpoint (ADR-002, option B2): rejected because it adds a second queue-writing path in the most safety-sensitive transition. The click saved isn't worth it.
  • Auto-reopening when the promised date passes (W2): rejected. There's no scheduler, and automatically creating sendable drafts is the line I won't cross without a human in the loop.
  • Rescheduling reminders until after the promised date (ADR-001, option B): deferred, not rejected. Phase 1 just skips the queue. Phase 2 later built a narrower version as a promises-due worklist with a manual reopen.

Evidence

Trade-off

The gates shrink the race but don't eliminate it. Approve reads the invoice status, looks up the customer, then calls Resend. A promise landing in those milliseconds can still result in one email. The payer action also isn't atomic: if queue cleanup fails after the status change, it returns 207 instead of rolling back, and the send-time re-check is the backstop.

DECISION 03

Retries and double clicks never produce a duplicate reminder

The problem

A double click, a network retry, or a database write that fails after a successful send could each produce a second email.

What I chose

  • A partial unique index allows at most one active (queued/sending) queue row per invoice per company.
  • The compare-and-set claim (queued → sending) means only one approver wins.
  • A deterministic Resend idempotency key built from stable ids: send:<company>:<queue-row>:<invoice>:<step>.
  • If bookkeeping fails after a successful send, the row stays "sent" and the API returns 207 with a warning. It is never marked failed and never retried automatically.
  • Webhook replays are absorbed by a unique constraint on the provider event id and answered 200.

Alternatives and why not

  • An automatic retry/outbox worker: not built. I chose at-most-once delivery with failures surfaced to a human, because at-least-once would need idempotency proven end to end first.
  • Marking the row "failed" on a post-send error: rejected, because "failed" invites a re-send of an email that was already delivered.
  • A denormalised delivery_status column on the queue table (ADR-005): rejected so the webhook never writes to the send-path table. Delivery status is derived at read time.

Evidence

Trade-off

At-most-once has a cost. If the "sent" update itself fails after the email has gone out, the row can stay in "sending" with no automatic recovery. That's safe (no re-send) but needs an operator. A re-queued invoice gets a new idempotency key by design, because the key includes the queue-row id.

KNOWN GAP / NOT YET CLOSED

Known gap: a promise can be recorded on a paid invoice

Writing this case study surfaced a gap in Decision 2. The payer action route updates the invoice status scoped on id and company, but with no precondition on the current status. A payer who opens the link for an invoice already marked Paid and submits a promise sets it to Promise. Reopen (Promise → draft) could then make a settled invoice sendable again.

Reaching an actual email still takes three operator actions — reopen, re-queue and approve — and nothing in PayLac sends on its own. The product isn't deployed, so no real invoice is exposed. But it breaks the guarantee that a paid invoice can never be dunned, and that guarantee should hold in the data, not depend on an operator noticing.

The fix is the pattern the reopen route already uses: put the status precondition in the same update statement, run it before the event row is written, and return 409 when zero rows match.

app/api/invoice/[token]/action/route.ts

sanitised excerpt
  // 6) Set the authoritative lifecycle status (Promise/Disputed). Scoped id+company_id.
  //    Both targets are non-sendable, so P1's send-gate backstops the queue cleanup.
  const { error: statusErr } = await db
    .from('invoices')
    .update({ status: resolution.status })
    .eq('id', invoiceId)
    .eq('company_id', companyId)

No status precondition: compare with the reopen route's .eq('status', 'Promise').

What I'd do next

  • Add the status precondition to the payer action route, plus tests for promise and dispute on a paid invoice
  • Add the missing gateCase('Promise') approve test
  • Scope the remaining id-only queries in approve on company_id
  • Move live verifiers to a separate staging database