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.
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
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
app/api/invoice/reopen-promise/route.ts
sanitised excerptexport async function POST(req: Request) {
// 1) Auth + tenant. companyId is ALWAYS session-derived, never from the body.
// No service-role operation runs before this succeeds.
let companyId: string
try {
;({ companyId } = await getSessionCompany())
} catch (e) {
if (e instanceof AuthError) {
return NextResponse.json({ error: e.message }, { status: e.status })
}
throw e
}
// … body parse + UUID validation → 400 before any DB client exists …
const admin = createClient(process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.SUPABASE_SERVICE_ROLE_KEY!, {
auth: { persistSession: false },
})
// 3) CORE — a single conditional CAS update: the status check AND the mutation
// happen in one statement. There is NO pre-fetch …
const { data: reopened, error: updErr } = await admin
.from('invoices')
.update({ status: 'draft' })
.eq('id', invoiceId)
.eq('company_id', companyId)
.eq('status', REOPENABLE_FROM_STATUS) // 'Promise'
.select('id')
// …
if (!reopened || reopened.length === 0) {
return NextResponse.json({ ok: false, error: 'not_reopenable' }, { status: 409 })
}supabase/migrations/008_invoice_actions_tenant_guard.sql
sanitised excerpt-- Composite parent-guard FK. Forces the (invoice_id, company_id) pair to exist
-- in invoices as a single row — making it impossible to write an action row for
-- the right company but a foreign invoice, even if route code regressed.
alter table public.invoice_actions
add constraint invoice_actions_invoice_tenant_fk
foreign key (invoice_id, company_id)
references public.invoices (id, company_id) on delete cascade;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
app/api/reminders/approve/route.ts
sanitised excerptconst SENDABLE_INVOICE_STATUSES = new Set(['draft'])
function isSendable(status: unknown): boolean {
return SENDABLE_INVOICE_STATUSES.has(String(status ?? '').trim().toLowerCase())
}
// …
// CAS lock: only rows that are still 'queued' and not expired are locked.
const { data: locked, error: lockErr } = await admin
.from('reminder_queue')
.update({ status: 'sending' })
.in('id', body.queue_ids)
.eq('company_id', companyId)
.eq('status', 'queued')
.gt('expires_at', new Date().toISOString())
.select('id, invoice_id, step, tone_context')
// …
// Send-gate (P1): only an explicitly sendable status sends. A draft that
// became Paid / Disputed / Promise after queueing is skipped, not dunned.
if (!isSendable(invoice.status)) {
await skipRow(row.id, `skipped_not_sendable:${String(invoice.status ?? 'null')}`)
continue
}
// Pause-gate (P3): … the invoice may have been paused after it was queued.
if (invoice.reminders_paused === true) {
await skipRow(row.id, 'skipped_reminders_paused')
continue
}app/api/invoice/[token]/action/route.ts
sanitised excerptconst ACTIVE_REMINDER_QUEUE_STATUSES = ['queued', 'sending'] as const
// …
// 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)
// …
// 8) Clean active reminder_queue rows so a promised/disputed invoice can't be dunned.
const { error: cleanupErr } = await db
.from('reminder_queue')
.update({ status: 'skipped', error: resolution.queue_error })
.eq('invoice_id', invoiceId)
.eq('company_id', companyId)
.in('status', ACTIVE_REMINDER_QUEUE_STATUSES as unknown as string[])
.select('id')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
supabase/migrations/004_queue_dedupe.sql
sanitised excerpt-- Queue-bridge dedupe guard: at most ONE active reminder per invoice.
-- … This partial
-- unique index makes double-queueing structurally impossible while an active
-- ('queued' or 'sending') row exists. Inactive rows ('sent', 'failed',
-- 'expired', 'skipped') don't block re-queueing.
create unique index if not exists reminder_queue_active_invoice_idx
on reminder_queue (company_id, invoice_id)
where status in ('queued', 'sending');app/api/reminders/approve/route.ts
sanitised excerpt // Deterministic idempotency key per send attempt. Built from immutable
// identifiers of THIS queue row (companyId + queue id + invoice id + step) …
// this is the second, provider-side line of defense — if a network retry
// ever replays the request, Resend dedupes on the Idempotency-Key header.
const idempotencyKey = `send:${companyId}:${row.id}:${row.invoice_id}:${row.step}`
const { data: sendData, error: sendErr } = await resend.emails.send(
{
from: sender.from,
to: customer.email,
subject,
html,
// …
},
{ idempotencyKey }
)
// …
// The send succeeded. Everything below is non-fatal post-send persistence:
// the email is already out, so NOTHING here may mark the row 'failed' or
// trigger a re-send (that would double-send). …
const { error: bookkeepingErr } = await admin
.from('invoices')
.update({ reminder_step: row.step, last_reminder_sent_at: new Date().toISOString() })
.eq('id', row.invoice_id)
.eq('company_id', companyId)
if (bookkeepingErr) warnings.push(`bookkeeping: ${bookkeepingErr.message}`)
// …
return NextResponse.json(
{ ok: bookkeepingWarnings === 0, /* … */ bookkeeping_warnings: bookkeepingWarnings, results },
{ status: bookkeepingWarnings > 0 ? 207 : 200 }
)app/api/webhooks/resend/route.ts
sanitised excerpt const { error: insertErr } = await admin.from('resend_email_events').insert({
svix_id: svixId,
event_type: record.event_type,
resend_email_id: record.resend_email_id,
reminder_queue_id: matched.id,
company_id: matched.company_id,
occurred_at: record.occurred_at,
raw_payload: record.raw_payload,
})
if (insertErr) {
// Duplicate delivery of the SAME webhook event (unique svix_id) → idempotent no-op, already
// recorded → 200. Any other insert error is unexpected and retryable → 500.
if ((insertErr as { code?: string }).code === '23505') {
return NextResponse.json({ ok: true, status: 'duplicate' }, { status: 200 })
}
return NextResponse.json({ error: 'Insert failed' }, { status: 500 })
}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').