Prompt Details
Model
Chat - (gpt-6-luna)
Token size
414
Example input
[Project Name]: FlowLedger
[Project Description]: Automated recurring invoice and payment reminder system for freelance agencies
[Tech Stack]: React, Python FastAPI, PostgreSQL
[Auth Method]: Clerk / OAuth2
[Expected Scale]: 5,000 monthly businesses
Example output
Act as a Principal Software Architect and Senior Full-Stack Engineer. Your task is to design a production-ready technical blueprint and starter codebase for the following project:
- Project Name: FlowLedger
- Core Purpose: Automated recurring invoice and payment reminder system for freelance agencies
- Target Tech Stack: React, Python FastAPI, PostgreSQL
- Authentication & Security Requirements: Clerk / OAuth2
- Scale & Performance Target: 5,000 monthly businesses
Execute the following 5 deliverables in strict sequential order without conversational filler:
1. **System Architecture & Data Flow**: Provide an ASCII architecture diagram showing the client, API gateway/backend, database, caching layer, and third-party integrations. Explain the request lifecycle in 4 concise bullet points.
2. **Database Schema & Indexing**: Write complete, copy-pasteable schema definitions (SQL DDL or Prisma/Mongoose models matching React, Python FastAPI, PostgreSQL) including primary/foreign keys, constraints, and composite indexes optimized for the top 3 read queries.
3. **API Contract Specification**: Present a Markdown table listing all core REST or GraphQL endpoints with columns for: Method & Route, Auth Required, Request Payload (JSON), Success Response (200/201), and Error Codes.
4. **Core Boilerplate Implementation**: Write clean, modular, production-grade code for the primary backend controller/service and one frontend integration hook, complete with input validation, error handling, and environment variable references.
5. **Security & Deployment Checklist**: List 5 specific security hardening steps (covering OWASP vulnerabilities relevant to Clerk / OAuth2) and a ready-to-use Dockerfile or CI/CD deployment configuration.
Constraints:
- Never use placeholder comments like // TODO: implement logic here inside code blocks; write complete, functional logic.
- Tailor all library choices, syntax, and best practices strictly to React, Python FastAPI, PostgreSQL.
FlowLedger — Production Technical Blueprint
Project: Recurring invoicing and payment reminders for freelance agencies
Stack: React, Python FastAPI, PostgreSQL, Clerk, Redis
Target: 5,000 monthly active businesses
Architecture decision: Start with a stateless modular monolith and separate background workers. This is simpler to operate than microservices at the target scale, while allowing the API and workers to scale independently.
1. System Architecture & Data Flow
Architecture diagram
┌───────────────────────────┐
│ Third Parties │
│ │
│ Clerk (Auth / Org IDs) │
│ Stripe (Payments) │
│ Email (Postmark/Resend) │
└─────────────┬─────────────┘
│
Webhooks / OAuth
│
┌──────────────────┐ ┌───────▼──────────────┐
│ React Client │ HTTPS │ Edge / API Gateway │
│ ├─────────►│ TLS, WAF, Rate Limit│
│ Clerk React SDK │ └────────┬─────────────┘
│ Dashboard │ │
│ Invoice UI │ ┌────────▼─────────────┐
│ Reminder UI │ │ FastAPI Backend │
└──────────────────┘ │ │
│ JWT Verification │
│ Tenant Authorization │
│ Invoice Services │
│ Payment Services │
│ Webhook Handlers │
└───┬─────────────┬────┘
│ │
┌───────────▼───┐ ┌─────▼────────────┐
│ PostgreSQL │ │ Redis │
│ │ │ │
│ Source of │ │ Short-lived Cache│
│ Truth │ │ Queue Broker │
│ Tenant RLS │ │ Distributed Locks│
│ Outbox Events │ └─────┬────────────┘
└───────────────┘ │
┌─────▼────────────┐
│ Background Worker│
│ │
│ Recurring Invoice│
│ Generation │
│ Reminder Delivery│
│ Retry Processing │
└──────────────────┘
Request lifecycle
Authentication: React obtains a short-lived Clerk session token and sends it as a Bearer token to FastAPI. The backend verifies its signature and claims, including the authorized-party origin where present.
Clerk Docs
+1
Tenant resolution: FastAPI obtains the active Clerk org_id from the verified token, maps it to a FlowLedger business, and establishes transaction-local PostgreSQL tenant context. Client-supplied tenant IDs are never treated as authorization.
Business operation: The API validates the request, applies tenant-scoped database access, and commits invoice/payment changes and corresponding outbox events in one transaction.
Asynchronous processing: Workers process recurring schedules, reminder jobs, and email delivery. Redis supports queues and short-lived caching; PostgreSQL remains the authoritative financial record.
Architectural decisions
Area
Choice
Reason
Frontend
React + Clerk React SDK
Session handling and organization selection
Backend
FastAPI modular monolith
Typed APIs, validation, async I/O
Database
PostgreSQL
Transactional financial records and row-level security
Cache / queue
Redis
Dashboard cache, task broker, distributed coordination
Background jobs
Celery worker + Beat
Recurring invoice and reminder processing
Payment integration
Stripe
Payment links and verified payment webhooks
Email integration
Postmark or Resend
Invoice and reminder delivery
Tenant model
One Clerk Organization per business
Signed organization context for tenant resolution
Important scaling rule: Cache dashboard summaries and frequently used reference data, not balances or payment state as the source of truth. Every cache key containing tenant data must include the business ID. Tenant isolation must also be enforced in the database, not just in application filters.
OWASP Cheat Sheet Series
2. Database Schema & Indexing
2.1 Data model
The database uses a shared PostgreSQL database with logical tenant isolation.
Core relationships
businesses
│
├── clients
│
├── recurring_series
│ └── recurring_series_items
│
├── invoices
│ ├── invoice_items
│ ├── payments
│ └── reminder_deliveries
│
├── reminder_rules
├── outbox_events
└── api_idempotency
webhook_events (platform-level)
Clerk owns user authentication and organization membership. FlowLedger stores the organization-to-business mapping.
2.2 Complete PostgreSQL DDL
Use this as the initial database migration. It uses integer minor currency units (for example, cents) instead of floating-point amounts, UUID primary keys, composite foreign keys, and tenant-level row security.
-- ==========================================================
-- FLOWLEDGER DATABASE SCHEMA
-- PostgreSQL 16+
-- ==========================================================
CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- ----------------------------------------------------------
-- 1. BUSINESSES
-- A Clerk Organization maps to one FlowLedger business.
-- ----------------------------------------------------------
CREATE TABLE businesses (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
clerk_org_id TEXT NOT NULL UNIQUE,
name VARCHAR(200) NOT NULL,
default_currency CHAR(3) NOT NULL DEFAULT 'USD',
timezone VARCHAR(100) NOT NULL DEFAULT 'UTC',
status VARCHAR(20) NOT NULL DEFAULT 'active'
CHECK (status IN ('active', 'suspended', 'cancelled')),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- ----------------------------------------------------------
-- 2. CLIENTS
-- ----------------------------------------------------------
CREATE TABLE clients (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
business_id UUID NOT NULL REFERENCES businesses(id),
name VARCHAR(200) NOT NULL,
email VARCHAR(320),
company_name VARCHAR(200),
billing_address JSONB NOT NULL DEFAULT '{}'::jsonb,
notes TEXT,
deleted_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (business_id, id)
);
CREATE INDEX idx_clients_business
ON clients (business_id, name)
WHERE deleted_at IS NULL;
-- ----------------------------------------------------------
-- 3. RECURRING SERIES
-- ----------------------------------------------------------
CREATE TABLE recurring_series (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
business_id UUID NOT NULL REFERENCES businesses(id),
client_id UUID NOT NULL,
name VARCHAR(200) NOT NULL,
cadence VARCHAR(20) NOT NULL
CHECK (cadence IN (
'weekly', 'monthly', 'quarterly', 'yearly'
)),
day_of_month SMALLINT
CHECK (day_of_month BETWEEN 1 AND 31),
starts_on DATE NOT NULL,
ends_on DATE,
next_period_start DATE NOT NULL,
next_period_end DATE NOT NULL,
next_run_at TIMESTAMPTZ NOT NULL,
currency CHAR(3) NOT NULL,
payment_terms_days SMALLINT NOT NULL DEFAULT 14
CHECK (payment_terms_days BETWEEN 0 AND 365),
status VARCHAR(20) NOT NULL DEFAULT 'active'
CHECK (status IN ('active', 'paused', 'completed')),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
FOREIGN KEY (business_id, client_id)
REFERENCES clients (business_id, id),
UNIQUE (business_id, id),
CHECK (ends_on IS NULL OR ends_on >= starts_on),
CHECK (next_period_end >= next_period_start)
);
CREATE TABLE recurring_series_items (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
business_id UUID NOT NULL REFERENCES businesses(id),
recurring_series_id UUID NOT NULL,
description VARCHAR(500) NOT NULL,
quantity NUMERIC(12,3) NOT NULL CHECK (quantity > 0),
unit_amount_minor BIGINT NOT NULL CHECK (unit_amount_minor >= 0),
sort_order INTEGER NOT NULL DEFAULT 0,
FOREIGN KEY (business_id, recurring_series_id)
REFERENCES recurring_series (business_id, id)
ON DELETE CASCADE
);
CREATE INDEX idx_recurring_due
ON recurring_series (next_run_at, id)
WHERE status = 'active';
-- ----------------------------------------------------------
-- 4. INVOICES
-- ----------------------------------------------------------
CREATE TABLE invoices (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
business_id UUID NOT NULL REFERENCES businesses(id),
client_id UUID NOT NULL,
recurring_series_id UUID,
invoice_number VARCHAR(80) NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'draft'
CHECK (status IN (
'draft', 'open', 'overdue', 'paid', 'void'
)),
issue_date DATE NOT NULL,
due_date DATE NOT NULL,
period_start DATE,
period_end DATE,
currency CHAR(3) NOT NULL,
subtotal_minor BIGINT NOT NULL CHECK (subtotal_minor >= 0),
tax_minor BIGINT NOT NULL DEFAULT 0 CHECK (tax_minor >= 0),
total_minor BIGINT NOT NULL CHECK (total_minor >= 0),
paid_minor BIGINT NOT NULL DEFAULT 0 CHECK (paid_minor >= 0),
balance_minor BIGINT GENERATED ALWAYS AS
(total_minor - paid_minor) STORED,
payment_url TEXT,
sent_at TIMESTAMPTZ,
notes TEXT,
created_by_clerk_user_id TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
FOREIGN KEY (business_id, client_id)
REFERENCES clients (business_id, id),
FOREIGN KEY (business_id, recurring_series_id)
REFERENCES recurring_series (business_id, id),
UNIQUE (business_id, id),
UNIQUE (business_id, invoice_number),
CHECK (due_date >= issue_date),
CHECK (paid_minor <= total_minor),
CHECK (period_end IS NULL OR period_start IS NOT NULL),
CHECK (
period_start IS NULL
OR period_end >= period_start
)
);
-- Prevent duplicate invoices for the same recurring period.
CREATE UNIQUE INDEX uq_recurring_invoice_period
ON invoices (
business_id,
recurring_series_id,
period_start
)
WHERE recurring_series_id IS NOT NULL;
-- Dashboard: outstanding and overdue invoices.
CREATE INDEX idx_invoices_dashboard
ON invoices (business_id, due_date ASC, id)
WHERE status IN ('open', 'overdue');
-- Client invoice history.
CREATE INDEX idx_invoice_client_history
ON invoices (
business_id,
client_id,
issue_date DESC,
id DESC
);
-- ----------------------------------------------------------
-- 5. INVOICE ITEMS
-- ----------------------------------------------------------
CREATE TABLE invoice_items (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
business_id UUID NOT NULL REFERENCES businesses(id),
invoice_id UUID NOT NULL,
description VARCHAR(500) NOT NULL,
quantity NUMERIC(12,3) NOT NULL CHECK (quantity > 0),
unit_amount_minor BIGINT NOT NULL CHECK (unit_amount_minor >= 0),
line_total_minor BIGINT NOT NULL CHECK (line_total_minor >= 0),
sort_order INTEGER NOT NULL DEFAULT 0,
FOREIGN KEY (business_id, invoice_id)
REFERENCES invoices (business_id, id)
ON DELETE CASCADE
);
CREATE INDEX idx_invoice_items_parent
ON invoice_items (business_id, invoice_id, sort_order);
-- ----------------------------------------------------------
-- 6. PAYMENTS
-- ----------------------------------------------------------
CREATE TABLE payments (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
business_id UUID NOT NULL REFERENCES businesses(id),
invoice_id UUID NOT NULL,
provider VARCHAR(30) NOT NULL
CHECK (provider IN (
'stripe', 'bank_transfer', 'manual'
)),
provider_payment_id TEXT,
amount_minor BIGINT NOT NULL CHECK (amount_minor > 0),
currency CHAR(3) NOT NULL,
status VARCHAR(20) NOT NULL
CHECK (status IN (
'pending', 'succeeded', 'failed', 'refunded'
)),
received_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
FOREIGN KEY (business_id, invoice_id)
REFERENCES invoices (business_id, id)
);
CREATE UNIQUE INDEX uq_payment_provider_reference
ON payments (provider, provider_payment_id)
WHERE provider_payment_id IS NOT NULL;
CREATE INDEX idx_payments_invoice
ON payments (business_id, invoice_id, created_at DESC);
-- ----------------------------------------------------------
-- 7. REMINDER RULES
-- Negative days_offset = before due date.
-- Positive days_offset = after due date.
-- ----------------------------------------------------------
CREATE TABLE reminder_rules (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
business_id UUID NOT NULL REFERENCES businesses(id),
days_offset INTEGER NOT NULL,
channel VARCHAR(20) NOT NULL DEFAULT 'email'
CHECK (channel IN ('email')),
active BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (business_id, days_offset, channel),
UNIQUE (business_id, id)
);
-- ----------------------------------------------------------
-- 8. REMINDER DELIVERIES
-- ----------------------------------------------------------
CREATE TABLE reminder_deliveries (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
business_id UUID NOT NULL REFERENCES businesses(id),
invoice_id UUID NOT NULL,
reminder_rule_id UUID NOT NULL,
scheduled_for TIMESTAMPTZ NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'pending'
CHECK (status IN (
'pending', 'sent', 'failed', 'cancelled'
)),
attempts SMALLINT NOT NULL DEFAULT 0,
sent_at TIMESTAMPTZ,
last_error TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
FOREIGN KEY (business_id, invoice_id)
REFERENCES invoices (business_id, id),
FOREIGN KEY (business_id, reminder_rule_id)
REFERENCES reminder_rules (business_id, id),
UNIQUE (business_id, invoice_id, reminder_rule_id, scheduled_for)
);
CREATE INDEX idx_reminder_due
ON reminder_deliveries (scheduled_for, id)
WHERE status = 'pending';
-- ----------------------------------------------------------
-- 9. TRANSACTIONAL OUTBOX
-- Records events in the same transaction as invoice changes.
-- ----------------------------------------------------------
CREATE TABLE outbox_events (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
business_id UUID NOT NULL REFERENCES businesses(id),
aggregate_type VARCHAR(50) NOT NULL,
aggregate_id UUID NOT NULL,
event_type VARCHAR(100) NOT NULL,
payload JSONB NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'pending'
CHECK (status IN (
'pending', 'processing', 'processed', 'failed'
)),
attempts SMALLINT NOT NULL DEFAULT 0,
available_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
processed_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_outbox_pending
ON outbox_events (available_at, id)
WHERE status IN ('pending', 'failed');
-- ----------------------------------------------------------
-- 10. API IDEMPOTENCY
-- ----------------------------------------------------------
CREATE TABLE api_idempotency (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
business_id UUID NOT NULL REFERENCES businesses(id),
idempotency_key VARCHAR(128) NOT NULL,
request_hash CHAR(64) NOT NULL,
response_body JSONB,
status_code SMALLINT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
UNIQUE (business_id, idempotency_key)
);
-- ----------------------------------------------------------
-- 11. PLATFORM WEBHOOK EVENTS
-- This table is managed by a restricted webhook processor.
-- Never expose it through tenant-facing endpoints.
-- ----------------------------------------------------------
CREATE TABLE webhook_events (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
provider VARCHAR(30) NOT NULL,
provider_event_id TEXT NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'received'
CHECK (status IN (
'received', 'processing', 'processed', 'failed'
)),
received_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
processed_at TIMESTAMPTZ,
last_error TEXT,
UNIQUE (provider, provider_event_id)
);
-- ==========================================================
-- 12. ROW LEVEL SECURITY
-- ==========================================================
-- Business lookup/insertion is restricted to the verified
-- Clerk organization in the active transaction.
ALTER TABLE businesses ENABLE ROW LEVEL SECURITY;
ALTER TABLE businesses FORCE ROW LEVEL SECURITY;
CREATE POLICY business_org_isolation ON businesses
USING (
clerk_org_id = current_setting(
'app.clerk_org_id', true
)
)
WITH CHECK (
clerk_org_id = current_setting(
'app.clerk_org_id', true
)
);
-- All tenant-owned tables use transaction-local business ID.
DO $$
DECLARE
table_name TEXT;
BEGIN
FOREACH table_name IN ARRAY ARRAY[
'clients',
'recurring_series',
'recurring_series_items',
'invoices',
'invoice_items',
'payments',
'reminder_rules',
'reminder_deliveries',
'outbox_events',
'api_idempotency'
]
LOOP
EXECUTE format(
'ALTER TABLE %I ENABLE ROW LEVEL SECURITY',
table_name
);
EXECUTE format(
'ALTER TABLE %I FORCE ROW LEVEL SECURITY',
table_name
);
EXECUTE format(
'CREATE POLICY tenant_isolation ON %I
USING (
business_id = NULLIF(
current_setting(
''app.business_id'', true
), ''''
)::uuid
)
WITH CHECK (
business_id = NULLIF(
current_setting(
''app.business_id'', true
), ''''
)::uuid
)',
table_name
);
END LOOP;
END $$;
2.3 Database role configuration
Run this using a database administrator account. Use a separate role for schema migrations.
CREATE ROLE flowledger_app
LOGIN
NOSUPERUSER
NOCREATEDB
NOCREATEROLE
NOINHERIT
NOBYPASSRLS;
GRANT CONNECT ON DATABASE flowledger TO flowledger_app;
GRANT USAGE ON SCHEMA public TO flowledger_app;
GRANT SELECT, INSERT, UPDATE, DELETE
ON ALL TABLES IN SCHEMA public TO flowledger_app;
GRANT USAGE, SELECT
ON ALL SEQUENCES IN SCHEMA public TO flowledger_app;
-- Keep platform-level webhook processing inaccessible to
-- ordinary tenant API requests.
REVOKE ALL ON webhook_events FROM flowledger_app;
Set equivalent default privileges for future objects owned by the migration role. Keep the migration owner separate from the runtime role.
PostgreSQL RLS is default-deny when no applicable policy permits access, but table owners and roles with BYPASSRLS need special treatment. This design forces RLS and uses a non-bypass application role.
PostgreSQL
+1
2.4 Top three read queries and indexes
Read query
SQL access pattern
Optimized index
Dashboard: outstanding invoices ordered by due date
business_id + status + due_date
idx_invoices_dashboard
Client invoice history
business_id + client_id + issue_date DESC
idx_invoice_client_history
Recurring invoices waiting for generation
status = active + next_run_at <= now()
idx_recurring_due
Query 1 — Outstanding invoices
SELECT
id, invoice_number, client_id,
due_date, currency, total_minor,
paid_minor, balance_minor, status
FROM invoices
WHERE business_id = $1
AND status IN ('open', 'overdue')
ORDER BY due_date ASC, id
LIMIT 50;
Query 2 — A client's invoice history
SELECT
id, invoice_number, issue_date,
due_date, total_minor, balance_minor, status
FROM invoices
WHERE business_id = $1
AND client_id = $2
ORDER BY issue_date DESC, id DESC
LIMIT 25;
Query 3 — Due recurring invoice jobs
SELECT id, business_id, next_period_start, next_period_end
FROM recurring_series
WHERE status = 'active'
AND next_run_at <= NOW()
ORDER BY next_run_at, id
LIMIT 100
FOR UPDATE SKIP LOCKED;
The third query is designed for concurrent workers. SKIP LOCKED prevents workers from blocking each other on already-claimed jobs. The unique recurring-period index provides a second layer of duplicate protection.
3. API Contract Specification
3.1 API conventions
Base URL: https://api.flowledger.com/v1
Authentication for tenant endpoints:
Authorization: Bearer <CLERK_SESSION_JWT>
Content-Type: application/json
All business endpoints require a valid Clerk session with an active org_id mapped to a FlowLedger business.
Standard error structure:
{
"error": {
"code": "INVOICE_NOT_FOUND",
"message": "The requested invoice does not exist."
}
}
3.2 Core REST endpoints
Method & Route
Auth Required
Request Payload (JSON)
Success Response (200/201)
Error Codes
POST /v1/onboarding
Clerk Bearer + active organization
{"name":"Acme Agency","currency":"USD","timezone":"Asia/Colombo"}
201 {"business_id":"uuid","name":"Acme Agency"}
401, 403, 409, 422
GET /v1/business
Clerk Bearer
None
200 {"id":"uuid","name":"Acme Agency","currency":"USD"}
401, 403, 404
GET /v1/dashboard
Clerk Bearer
Query: ?from=2026-11-01&to=2026-11-30
200 {"outstanding_minor":120000,"overdue_minor":25000,"paid_minor":50000,"invoice_count":12}
401, 403, 422
GET /v1/clients
Clerk Bearer
Query: ?limit=25&search=acme
200 {"data":[{"id":"uuid","name":"Acme","email":"billing@acme.com"}]}
401, 403, 422
POST /v1/clients
Clerk Bearer
{"name":"Acme","email":"billing@acme.com","company_name":"Acme Ltd"}
201 {"id":"uuid","name":"Acme"}
401, 403, 409, 422
PATCH /v1/clients/{id}
Clerk Bearer
{"name":"Acme Ltd","email":"accounts@acme.com"}
200 {"id":"uuid","name":"Acme Ltd"}
401, 403, 404, 422
GET /v1/recurring-series
Clerk Bearer
Query: ?status=active
200 {"data":[{"id":"uuid","name":"Monthly retainer","cadence":"monthly"}]}
401, 403, 422
POST /v1/recurring-series
Clerk Bearer
{"client_id":"uuid","name":"Monthly retainer","cadence":"monthly","currency":"USD","items":[{"description":"Development","quantity":10,"unit_amount_minor":5000}]}
201 {"id":"uuid","status":"active","next_run_at":"2026-12-01T00:00:00Z"}
401, 403, 404, 409, 422
PATCH /v1/recurring-series/{id}
Clerk Bearer
{"status":"paused"}
200 {"id":"uuid","status":"paused"}
401, 403, 404, 422
GET /v1/invoices
Clerk Bearer
Query: ?status=overdue&limit=25
200 {"data":[{"id":"uuid","invoice_number":"FL-2026-001","balance_minor":25000,"status":"overdue"}]}
401, 403, 422
POST /v1/invoices
Clerk Bearer + Idempotency-Key
{"client_id":"uuid","invoice_number":"FL-2026-002","issue_date":"2026-11-20","due_date":"2026-12-04","currency":"USD","items":[{"description":"Web development","quantity":10,"unit_amount_minor":5000}]}
201 {"id":"uuid","invoice_number":"FL-2026-002","total_minor":50000,"balance_minor":50000,"status":"draft"}
401, 403, 404, 409, 422
GET /v1/invoices/{id}
Clerk Bearer
None
200 {"id":"uuid","invoice_number":"FL-2026-002","items":[],"total_minor":50000,"balance_minor":50000}
401, 403, 404
POST /v1/invoices/{id}/send
Clerk Bearer
{"send_email":true}
200 {"id":"uuid","status":"open","email_queued":true}
401, 403, 404, 409
GET /v1/reminder-rules
Clerk Bearer
None
200 {"data":[{"days_offset":-3,"channel":"email"},{"days_offset":3,"channel":"email"}]}
401, 403
PUT /v1/reminder-rules
Clerk Bearer
{"rules":[{"days_offset":-3,"channel":"email"},{"days_offset":1,"channel":"email"},{"days_offset":7,"channel":"email"}]}
200 {"updated":3}
401, 403, 422
GET /v1/invoices/{id}/payments
Clerk Bearer
None
200 {"data":[{"id":"uuid","amount_minor":25000,"status":"succeeded"}]}
401, 403, 404
POST /v1/invoices/{id}/payments
Clerk Bearer + authorized business role
{"amount_minor":25000,"currency":"USD","provider":"bank_transfer"}
201 {"id":"uuid","status":"succeeded","balance_minor":25000}
401, 403, 404, 409, 422
POST /v1/webhooks/stripe
Stripe signature verification; no Clerk token
Stripe event JSON; raw body required for signature verification
200 {"received":true}
400, 401, 409, 500
3.3 API behavior rules
Money representation
All amounts are integer minor units.
For example:
{
"currency": "USD",
"total_minor": 125050
}
This represents USD 1,250.50.
Idempotency
For invoice creation:
POST /v1/invoices
Idempotency-Key: 0a8bc4f2-2e31-4abd-a673-b25b7c20f590
Repeated requests with the same key and identical payload return the original result. A different payload with the same key returns 409 IDEMPOTENCY_CONFLICT.
Payment integrity
Stripe payment confirmations must come from verified webhook events. A frontend success redirect must never independently mark an invoice as paid. Webhook processing must be idempotent using the provider's event ID and payment ID.
Recurring invoice generation
The scheduler creates invoices using the recurring period key. Each generation transaction must:
Lock an active recurring series.
Generate the invoice and invoice items.
Insert the corresponding outbox event.
Advance the next billing period.
Commit all changes together.
4. Core Boilerplate Implementation
4.1 Recommended project structure
flowledger/
│
├── frontend/
│ ├── src/
│ │ ├── hooks/
│ │ │ └── useInvoices.ts
│ │ ├── components/
│ │ ├── pages/
│ │ └── main.tsx
│ └── .env.example
│
├── backend/
│ ├── app/
│ │ ├── main.py
│ │ ├── config.py
│ │ ├── security.py
│ │ ├── database.py
│ │ ├── schemas.py
│ │ ├── routers/
│ │ │ └── invoices.py
│ │ └── services/
│ │ └── invoice_service.py
│ ├── requirements.txt
│ ├── Dockerfile
│ └── .env.example
│
├── database/
│ └── 001_initial_schema.sql
│
└── docker-compose.yml
4.2 Backend dependencies
backend/requirements.txt
fastapi>=0.115,<1.0
uvicorn[standard]>=0.30
asyncpg>=0.30
PyJWT[crypto]>=2.10
pydantic>=2.9
pydantic-settings>=2.6
email-validator>=2.2
4.3 Environment configuration
backend/app/config.py
from functools import lru_cache
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
extra="ignore",
)
database_url: str
clerk_jwks_url: str
clerk_issuer: str
clerk_authorized_parties: str
clerk_audience: str | None = None
clerk_require_azp: bool = True
frontend_origins: str
@property
def allowed_parties(self) -> list[str]:
return [
item.strip()
for item in self.clerk_authorized_parties.split(",")
if item.strip()
]
@property
def allowed_origins(self) -> list[str]:
return [
item.strip()
for item in self.frontend_origins.split(",")
backend/.env.example
DATABASE_URL=postgresql://flowledger_app:CHANGE_ME@postgres:5432/flowledger
CLERK_JWKS_URL=https://YOUR_CLERK_FRONTEND_API/.well-known/jwks.json
CLERK_ISSUER=https://YOUR_CLERK_FRONTEND_API
CLERK_AUTHORIZED_PARTIES=https://app.flowledger.com
CLERK_AUDIENCE=flowledger-api
CLERK_REQUIRE_AZP=true
FRONTEND_ORIGINS=https://app.flowledger.com
Configure the Clerk JWT template/session claims to include the audience flowledger-api, and configure the API's accepted issuer, JWKS URL, and frontend origins to match your actual Clerk instance. Do not copy the example values into production.
4.4 Clerk JWT authentication
backend/app/security.py
from dataclasses import dataclass
import jwt
from fastapi import Depends, HTTPException
from fastapi.security import (
HTTPAuthorizationCredentials,
HTTPBearer,
)
from starlette.concurrency import run_in_threadpool
from app.config import get_settings
bearer_scheme = HTTPBearer(auto_error=False)
@dataclass(frozen=True)
class Principal:
user_id: str
org_id: str
org_role: str
session_id: str
async def get_current_principal(
credentials: HTTPAuthorizationCredentials | None = Depends(
bearer_scheme
),
) -> Principal:
settings = get_settings()
if credentials is None:
raise HTTPException(
status_code=401,
This verifies the Clerk JWT signature, issuer, expiration, optional configured audience, and authorized party. JWKS keys are obtained through the Clerk JWKS endpoint. The JWKS client should be shared and cached in a production refinement rather than instantiated per request; the request-level pattern above is a functional starting point, but the shared-cache refinement is preferable for sustained throughput.
Clerk Docs
+1
4.5 PostgreSQL tenant connection
backend/app/database.py
from dataclasses import dataclass
from uuid import UUID
import asyncpg
from fastapi import Depends, HTTPException, Request
from app.security import Principal, get_current_principal
@dataclass
class TenantContext:
conn: asyncpg.Connection
business_id: UUID
clerk_user_id: str
org_role: str
async def get_tenant_context(
request: Request,
principal: Principal = Depends(get_current_principal),
):
pool: asyncpg.Pool = request.app.state.pool
async with pool.acquire() as conn:
async with conn.transaction():
# Transaction-local organization scope.
await conn.fetchval(
"SELECT set_config('app.clerk_org_id', $1, true)",
principal.org_id,
)
business = await conn.fetchrow(
"""
The transaction remains open while the endpoint runs. PostgreSQL resets the tenant settings when the transaction finishes because set_config(..., true) is transaction-local. This prevents one tenant's context from leaking into another request using the pooled connection.
PostgreSQL
+1
4.6 Input validation schemas
backend/app/schemas.py
from datetime import date
from decimal import Decimal
from typing import Literal
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, model_validator
class InvoiceItemInput(BaseModel):
model_config = ConfigDict(extra="forbid")
description: str = Field(min_length=1, max_length=500)
quantity: Decimal = Field(
gt=0,
max_digits=12,
decimal_places=3,
)
unit_amount_minor: int = Field(
ge=0,
le=9_000_000_000_000,
)
class InvoiceCreate(BaseModel):
model_config = ConfigDict(extra="forbid")
client_id: UUID
invoice_number: str = Field(
min_length=1,
max_length=80,
pattern=r"^[A-Za-z0-9._/-]+$",
)
issue_date: date
4.7 Invoice service
This service implements three important behaviors:
Validates that the client belongs to the active business.
Calculates invoice totals without floating-point arithmetic.
Creates the invoice, invoice items, idempotency result, and outbox event inside the same database transaction.
backend/app/services/invoice_service.py
import hashlib
import json
from decimal import Decimal, ROUND_HALF_UP
from uuid import UUID, uuid4
import asyncpg
from app.schemas import InvoiceCreate
class ServiceError(Exception):
def __init__(self, status_code: int, code: str, message: str):
self.status_code = status_code
self.code = code
self.message = message
super().__init__(message)
def json_object(value):
if isinstance(value, str):
return json.loads(value)
return value
class InvoiceService:
@staticmethod
async def create_invoice(
conn: asyncpg.Connection,
business_id: UUID,
clerk_user_id: str,
idempotency_key: str,
payload: InvoiceCreate,
) -> dict:
Transaction guarantee: The API dependency owns the transaction. If invoice insertion, item insertion, outbox insertion, or idempotency persistence fails, the entire transaction rolls back. This prevents partially created invoices.
4.8 FastAPI invoice controller
backend/app/routers/invoices.py
from typing import Literal
import asyncpg
from fastapi import APIRouter, Depends, Header, Query
from app.database import TenantContext, get_tenant_context
from app.schemas import InvoiceCreate, InvoiceResponse
from app.services.invoice_service import (
InvoiceService,
ServiceError,
)
router = APIRouter(
prefix="/v1/invoices",
tags=["Invoices"],
)
@router.post(
"",
response_model=InvoiceResponse,
status_code=201,
)
async def create_invoice(
payload: InvoiceCreate,
idempotency_key: str = Header(
alias="Idempotency-Key",
min_length=16,
max_length=128,
),
tenant: TenantContext = Depends(get_tenant_context),
):
try:
4.9 FastAPI application entry point
backend/app/main.py
from contextlib import asynccontextmanager
import logging
import asyncpg
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from app.config import get_settings
from app.routers.invoices import router as invoice_router
from app.services.invoice_service import ServiceError
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("flowledger")
@asynccontextmanager
async def lifespan(app: FastAPI):
settings = get_settings()
app.state.pool = await asyncpg.create_pool(
dsn=settings.database_url,
min_size=2,
max_size=10,
command_timeout=30,
max_inactive_connection_lifetime=300,
)
yield
await app.state.pool.close()
4.10 React frontend integration hook
The React hook uses Clerk's getToken() and maintains invoice state. It does not store authentication tokens in local storage or manually manage refresh tokens.
frontend/src/hooks/useInvoices.ts
import {
useCallback,
useEffect,
useState,
} from "react";
import { useAuth } from "@clerk/clerk-react";
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
interface Invoice {
id: string;
invoice_number: string;
status: string;
issue_date: string;
due_date: string;
currency: string;
total_minor: number;
paid_minor: number;
balance_minor: number;
}
interface InvoiceListResponse {
data: Invoice[];
}
interface InvoiceCreatePayload {
client_id: string;
invoice_number: string;
issue_date: string;
due_date: string;
currency: string;
items: {
description: string;
quantity: number;
unit_amount_minor: number;
}[];
}
interface ApiError {
error?: {
code?: string;
message?: string;
};
}
export function useInvoices() {
const { getToken, isLoaded, isSignedIn } = useAuth();
const [invoices, setInvoices] = useState<Invoice[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const apiRequest = useCallback(
async <T,>(
path: string,
options: RequestInit = {},
): Promise<T> => {
if (!API_BASE_URL) {
throw new Error("VITE_API_BASE_URL is not configured");
}
const token = await getToken();
if (!token) {
throw new Error("Authentication required");
}
const response = await fetch(
`${API_BASE_URL}/v1${path}`,
{
...options,
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
...options.headers,
},
},
);
const result = await response.json() as T | ApiError;
if (!response.ok) {
const apiError = result as ApiError;
throw new Error(
apiError.error?.message ??
`Request failed with status ${response.status}`,
);
}
return result as T;
},
[getToken],
);
const refresh = useCallback(
async (signal?: AbortSignal) => {
if (!isLoaded || !isSignedIn) {
return;
}
setLoading(true);
setError(null);
try {
const result = await apiRequest<InvoiceListResponse>(
"/invoices",
{
method: "GET",
signal,
},
);
if (!signal?.aborted) {
setInvoices(result.data);
}
} catch (err) {
if (!signal?.aborted) {
setError(
err instanceof Error
? err.message
: "Unable to retrieve invoices",
);
}
} finally {
if (!signal?.aborted) {
setLoading(false);
}
}
},
[apiRequest, isLoaded, isSignedIn],
);
const createInvoice = useCallback(
async (payload: InvoiceCreatePayload) => {
setError(null);
try {
const result = await apiRequest<Invoice>(
"/invoices",
{
method: "POST",
headers: {
"Idempotency-Key": crypto.randomUUID(),
},
body: JSON.stringify(payload),
},
);
await refresh();
return result;
} catch (err) {
const message =
err instanceof Error
? err.message
: "Unable to create invoice";
setError(message);
throw err;
}
},
[apiRequest, refresh],
);
useEffect(() => {
if (!isLoaded) {
return;
}
if (!isSignedIn) {
setInvoices([]);
setLoading(false);
return;
}
const controller = new AbortController();
void refresh(controller.signal);
return () => {
controller.abort();
};
}, [isLoaded, isSignedIn, refresh]);
return {
invoices,
loading,
error,
refresh,
createInvoice,
};
}
frontend/.env.example
VITE_API_BASE_URL=https://api.flowledger.com
Example frontend usage:
import { useInvoices } from "./hooks/useInvoices";
export function InvoiceDashboard() {
const {
invoices,
loading,
error,
createInvoice,
} = useInvoices();
if (loading) return <p>Loading invoices...</p>;
if (error) return <p>{error}</p>;
return (
<section>
<h2>Invoices ({invoices.length})</h2>
{invoices.map(invoice => (
<article key={invoice.id}>
<strong>{invoice.invoice_number}</strong>
<span>{invoice.status}</span>
<span>
{invoice.currency}{" "}
{(invoice.balance_minor / 100).toFixed(2)}
</span>
</article>
))}
</section>
);
}
4.11 Two production integration patches
A. Cache the Clerk JWKS client
Use a shared JWKS client rather than constructing one for every API request. Replace the corresponding initialization in security.py with:
from functools import lru_cache
@lru_cache(maxsize=1)
def get_jwks_client():
settings = get_settings()
return jwt.PyJWKClient(settings.clerk_jwks_url)
Then use:
signing_key = await run_in_threadpool(
get_jwks_client().get_signing_key_from_jwt,
token,
)
This allows the client to reuse its JWKS cache and reduces unnecessary network requests.
B. Business onboarding endpoint
Add this schema to schemas.py:
class BusinessOnboarding(BaseModel):
model_config = ConfigDict(extra="forbid")
name: str = Field(min_length=2, max_length=200)
currency: str = Field(default="USD", pattern=r"^[A-Z]{3}$")
timezone: str = Field(default="UTC", min_length=1, max_length=100)
Add this endpoint to main.py:
from fastapi import Depends
from app.security import Principal, get_current_principal
from app.schemas import BusinessOnboarding
@app.post("/v1/onboarding", status_code=201)
async def onboard_business(
payload: BusinessOnboarding,
principal: Principal = Depends(get_current_principal),
):
pool = app.state.pool
async with pool.acquire() as conn:
async with conn.transaction():
await conn.fetchval(
"SELECT set_config('app.clerk_org_id', $1, true)",
principal.org_id,
)
business = await conn.fetchrow(
"""
INSERT INTO businesses (
clerk_org_id,
name,
default_currency,
timezone
)
VALUES ($1, $2, $3, $4)
ON CONFLICT (clerk_org_id)
DO UPDATE SET updated_at = NOW()
RETURNING id, name, default_currency, timezone
""",
principal.org_id,
payload.name,
payload.currency,
The onboarding operation uses the verified Clerk organization claim, so a frontend cannot create or select another tenant simply by submitting a different business ID.
C. Use the configured JWT template in React
Because the backend configuration expects the audience flowledger-api, change the React hook's token acquisition to:
const token = await getToken({
template: "flowledger-api",
});
Create a matching Clerk JWT template named flowledger-api with the audience claim set to flowledger-api. Keep the organization context in the verified session claims.
5. Security & Deployment Checklist
5.1 Five security hardening steps
1. Secure OAuth2 / OpenID Connect authentication
Use Clerk-managed authorization code flows with PKCE. Keep redirect URIs on an exact allowlist, validate issuer and client configuration, and prevent arbitrary post-login redirect URLs.
Validate transaction-specific state and OIDC nonce through the authentication provider's supported flow. Do not implement the OAuth implicit grant or password grant. Never expose client secrets in React.
Reference: OWASP OAuth 2.0 Security Cheat Sheet.
OWASP Cheat Sheet Series
2. Enforce JWT validation and secure session handling
Validate every token's signature, permitted algorithm, iss, aud, exp, nbf, and authorized-party claim. Cache Clerk JWKS keys, support key rotation, and reject expired or pending sessions.
Use short-lived session tokens, avoid browser local-storage token persistence, and require fresh authentication for sensitive business administration operations where appropriate.
Reference: Clerk manual JWT verification.
Clerk Docs
+1
3. Prevent cross-tenant access and IDOR vulnerabilities
Every tenant-owned record must have a business association. Enforce PostgreSQL RLS, use a non-superuser runtime role with NOBYPASSRLS, and set tenant identity through transaction-local configuration.
Never trust business_id, org_id, or resource ownership identifiers supplied in request JSON. Verify ownership of clients, invoices, recurring series, and payments. Test requests that deliberately substitute IDs belonging to another tenant.
Cache keys must also include the business ID.
Reference: OWASP Multi-Tenant Security.
OWASP Cheat Sheet Series
+1
4. Secure CORS, cookies and CSRF
Allow only explicitly configured production frontend origins. Keep allow_credentials=False when using the Authorization Bearer header pattern shown in this starter.
Do not assume CORS alone prevents CSRF. If a future integration authenticates using cookies, use Secure, HttpOnly, and appropriate SameSite attributes, plus a validated CSRF-token or equivalent defense.
Reference: OWASP CSRF and CORS security guidance.
OWASP Cheat Sheet Series
+1
5. Harden payments, webhooks and API inputs
Verify Stripe webhook signatures using the unmodified raw HTTP request body. Persist provider event IDs under a unique constraint, reject duplicate processing, and make payment updates transactional.
Use Pydantic validation, parameterized SQL, request-size limits, per-business rate limits, and API quotas. Use Stripe-hosted payment collection so FlowLedger never needs to store card numbers or CVVs. Keep API secrets in a secrets manager and enforce HTTPS.
Monitor failed logins, authorization failures, repeated payment callbacks, and abnormal request volumes.
5.2 Ready-to-use Dockerfile
backend/Dockerfile
FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
WORKDIR /app
# Create a non-root runtime user.
RUN groupadd --system flowledger \
&& useradd --system \
--gid flowledger \
--create-home flowledger
# Install Python dependencies.
COPY requirements.txt .
RUN pip install --no-cache-dir --upgrade pip \
&& pip install --no-cache-dir -r requirements.txt
# Copy application source.
COPY app/ ./app/
# Run as a non-root user.
USER flowledger
EXPOSE 8000
HEALTHCHECK \
--interval=30s \
--timeout=5s \
--start-period=15s \
--retries=3 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health/live', timeout=3)" || exit 1
CMD ["uvicorn", "app.main:app", \
"--host", "0.0.0.0", \
"--port", "8000", \
"--workers", "1"]
Build and run:
cd flowledger/backend
docker build -t flowledger-api:1.0.0 .
docker run -d \
--name flowledger-api \
--restart unless-stopped \
-p 8000:8000 \
--env-file .env \
flowledger-api:1.0.0
Check the application:
curl http://localhost:8000/health/live
Expected:
{
"status": "alive"
}
5.3 Production deployment topology
Recommended deployment layout
Cloud Load Balancer / WAF
TLS termination · Rate limiting · Request filtering
API replicas
2–3
FastAPI containers
Worker replicas
2
Celery workers and scheduler
Managed PostgreSQL
Primary database · Backups · RLS
Managed Redis
Cache · Queue · Coordination
The replica counts are initial deployment sizing suggestions, not measured capacity guarantees. Use load testing to determine the appropriate number of API and worker instances.
5.4 Deployment environment variables
Variable
Purpose
DATABASE_URL
PostgreSQL connection string
CLERK_JWKS_URL
Clerk public signing keys
CLERK_ISSUER
JWT issuer validation
CLERK_AUDIENCE
API audience verification
CLERK_AUTHORIZED_PARTIES
Permitted frontend origins
VITE_API_BASE_URL
React API destination
REDIS_URL
Cache and task broker connection
STRIPE_SECRET_KEY
Payment API integration
STRIPE_WEBHOOK_SECRET
Webhook signature verification
EMAIL_API_KEY
Transactional email provider
Keep all backend secrets out of the frontend environment. Only VITE_ variables intended to be public should be bundled into React.
5.5 Operational release checklist
Area
Required before production
Database
Apply migrations using a separate migration role
Database security
Verify RLS with two different business accounts
Authentication
Test expired tokens, wrong audience, wrong issuer and invalid organization claims
Payments
Test successful, failed, duplicate and delayed payment webhooks
Recurring billing
Test month-end dates, leap years, timezone boundaries and worker retries
Email
Verify SPF, DKIM, DMARC and bounce processing
Reliability
Configure backups, point-in-time recovery and alerting
Observability
Centralized logs, request IDs, latency metrics and error tracking
Performance
Test dashboard queries, connection pool saturation and concurrent workers
Deployment
Use immutable images, health checks, rolling deployment and migration rollback procedures
5.6 Implementation scope and launch gates
The supplied code implements the authentication foundation, tenant context, business onboarding, invoice creation, invoice listing, idempotency, and the React integration hook.
The remaining services must be completed before enabling the corresponding production features:
Component
Required implementation
Recurring worker
Celery task to generate invoices and advance billing schedules
Reminder worker
Schedule, deliver, retry and record reminder emails
Stripe webhook
Raw-body signature verification and payment reconciliation
Email service
Postmark/Resend integration and delivery tracking
Client management
Complete CRUD controller and service
Recurring management
Complete CRUD, pause/resume and schedule validation
Dashboard
Aggregation queries and tenant-aware Redis cache
Add these dependencies when implementing the integrations:
celery[redis]>=5.4
redis>=5.0
stripe>=11
Database connection planning: The initial API configuration allows up to 10 connections per application process. Calculate the total possible connections across all replicas and workers before setting the PostgreSQL connection limit. Use a managed connection pooler when necessary.
Recommended launch sequence: Database migrations → Clerk onboarding → client management → invoice creation → recurring worker → payment integration → reminder delivery → security testing → production deployment.
The proposed architecture is appropriate as a starting point for 5,000 monthly businesses. Actual production capacity must be established through concurrent-user, database, queue and webhook load testing.
By purchasing this prompt, you agree to our terms of service
GPT-6-LUNA
Generate a structured technical architecture blueprint and starter code scaffolding for your software project. Outputs an ASCII system architecture diagram, draft database schema with suggested indexes, REST/GraphQL API endpoint specification table, modular backend and frontend starter code templates, OWASP security review checklist, and sample deployment config tailored to your stack and scale. Ideal for developers planning MVPs and system designs.
...more
Added 17 hours ago
