Architecture Overview — Cardsite Link Manager
System Architecture
Cloudflare / Caddy (TLS, HSTS)
│
┌────────────────┴────────────────┐
│ │
┌────────▼─────────┐ ┌───────▼────────┐
│ React + Vite │ │ Go API │
│ Static (Caddy) │ │ :18810 │
└────────┬─────────┘ └───────┬────────┘
│ │
│ REST + JSON (JWT bearer) │
└────────────────► ◄──────────────┘
│
┌───────────────────────┼───────────────────────┐
│ │ │
┌────────▼────────┐ ┌─────────▼─────────┐ ┌────────▼────────┐
│ PostgreSQL 16 │ │ Redis 7 (cache, │ │ S3-compatible │
│ (61 tables, │ │ optional, nil- │ │ object storage │
│ 44 migrations) │ │ safe Cacher) │ │ (SigV4, no SDK) │
└────────┬────────┘ └───────────────────┘ └─────────────────┘
│
┌─────────┴─────────┐
│ job_queue (P2-2) ─┼─► 3 worker goroutines (SKIP LOCKED, retries)
│ webhook_logs │
│ admin_logs │
│ idempotency_keys │
│ email_bounces │
│ feature_flags │
└───────────────────┘
The Go port is the product. The PHP tree it replaced is archived reference under .archives/removal-safe/references/php and is not built or deployed. Release history is in CHANGELOG.md.
Backend Architecture (Go)
Layered Design
HTTP Request
│
▼
[Middleware chain]
RequestID → Logger (slog) → Recoverer →
SecurityHeaders → CSRFGuard → Maintenance → Blacklist →
Auth (JWT or API key) → RateLimit (global, auth, AI quota) →
Idempotency → AdminAudit (admin scope only)
│
▼
[Handlers] 127 files — consumer-side store interfaces, JSON envelope helpers
│
▼
[Services] Business logic — payment gateways, AI, email, jobs, storage,
totp, geoip, oauth, captcha, cache, cron, qrcode, display_rules,
plan_limits, ratelimit_config
│
▼
[Repository] 52 pgx data-access files (pooled pgxpool)
│
▼
[Database] PostgreSQL 16 — 61 tables across 44 migrations
Package Structure
| Package | Purpose |
|---|---|
cmd/server | Entry point — 416 routes, full DI wiring, server lifecycle |
internal/handlers | 127 HTTP handler files + tests |
internal/services | Business logic, external integrations |
internal/repository | 52 pgx data-access files |
internal/models | 40+ domain models, JSONMap, typed schemas |
internal/middleware | Auth, ratelimit, CSRF, security headers, admin audit, idempotency, maintenance, blacklist, request_id, logging |
internal/config | Env-based configuration struct |
Handler interface pattern
Each handler declares the narrow store interface it needs. The repository struct implements many such interfaces. Tests substitute a mock — handler tests run with no database dependency.
type LinkStore interface {
GetByID(ctx context.Context, id int64) (*models.Link, error)
ListByUserID(ctx context.Context, userID int64, page, perPage int) ([]*models.Link, int, error)
Create(ctx context.Context, link *models.Link) error
Update(ctx context.Context, link *models.Link) error
Delete(ctx context.Context, id, userID int64) error
}
type LinkHandler struct {
links LinkStore
cache Cacher
}
Authentication
| Method | Where |
|---|---|
| JWT (HS256, 24 h) | middleware/auth.go — extracts Authorization: Bearer …, populates userID + userType in context |
| API key (long-lived bearer) | Same middleware; falls back to API key lookup if JWT parse fails |
| OAuth | Google, Facebook, Discord, LinkedIn, Microsoft — the five providers whose client credentials config/config.go reads (services/oauth.go) |
| 2FA (TOTP) | services/totp.go — POST /api/v1/auth/2fa/setup returns provisioning URI; verify activates; login challenge step rendered when enabled |
| Admin gate | middleware/RequireAdmin — checks users.type = 1 |
Session invalidation: password reset rotates the user's API key.
Payment Processing
Registry-based PaymentGateway interface (services/payment.go) with 22 implementations. Each implements:
type PaymentGateway interface {
Name() string
CreateCheckoutSession(ctx context.Context, params CheckoutParams) (*CheckoutResult, error)
HandleWebhook(ctx context.Context, payload []byte, signature string) (*WebhookResult, error)
CancelSubscription(ctx context.Context, subscriptionID string) error
}
Gateways: Stripe, PayPal, Razorpay, Coinbase Commerce, Mollie, Paddle, Paddle Billing, Paystack, PayU, Mercado Pago, Midtrans, Iyzico, Flutterwave, Klarna, LemonSqueezy, MyFatoorah, Plisio, Plisio Whitelabel, Revolut, Crypto.com, YooKassa, offline payment. cmd/server/main.go registers 21 at startup; paddle_billing is compiled but not registered (its implementation is incomplete, and startup logs that).
WebhookHandler records every event to webhook_logs (migration 000014, unique (gateway, external_id)) — duplicates rejected before processing. HMAC-SHA256 signature verification on every gateway with secret support.
Background Jobs (P2-2)
services/jobs.go → JobQueue:
- Persistent: rows in PostgreSQL
job_queuetable (migration 000020) - Concurrency: 3 worker goroutines, each polling with
SELECT … FOR UPDATE SKIP LOCKED LIMIT 1 - Retries: exponential back-off (
2^attemptminutes) up tomax_attempts - Reaper: separate goroutine resets
runningrows older than 10 minutes - Multi-replica safe by design (advisory locks via
FOR UPDATE SKIP LOCKED) - Handlers registered at startup:
send_email,broadcast_email,ai_image_generate
In addition, a scheduled cron service runs in-process for periodic maintenance:
- Subscription expiry check (hourly)
- Tracking data cleanup (daily, 365-day retention)
- User activity log cleanup (daily, 90-day retention)
- Expired discount code deactivation (daily)
- Read notification cleanup (weekly, 30-day retention)
- User
last_activitysync (every 30 minutes) cleanup_idempotency_keys(daily; purges expired idempotency rows)
Caching Strategy
- Redis at the handler level (not repository) for clear invalidation. Hot paths: redirect lookup, public biolink JSON, plans, statistics. Graceful nil-safe fallback when Redis is unavailable —
Cacherinterface ininternal/services/cache.go. - Cache invalidation tags (P3-1): every cache write is keyed by resource type so mutations can wipe a coherent slice in one call.
- Frontend TanStack Query (P3-2) —
staleTime=30s,gcTime=5min, resource-scoped invalidation on mutation; block-types/feature-flags usestaleTime: Infinity.
Observability (P2-1, P2-15)
- Logging:
log/slogJSON in production withrequest_id,user_id,method,path,status,durationon every line. - Request ID: custom
middleware.RequestIDgenerates a 16-hex-char ID, setsX-Request-IDresponse header, propagates via context. - Metrics:
GET /metricsPrometheus text —requests_total,errors_total,uptime_seconds,goroutines,heap_alloc_bytes. - Readiness:
GET /readyreturns{status, checks: {db: ok|fail}}. - Admin audit: every admin POST/PUT/PATCH/DELETE persists to
admin_logs(migration 000017) viamiddleware/admin_audit.go(fire-and-forget goroutine).
Security Middleware (P2-7, P0-7)
| Middleware | Behavior |
|---|---|
SecurityHeaders | X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy: strict-origin-when-cross-origin |
CSRFGuard | Rejects state-changing requests missing X-Requested-With: XMLHttpRequest. Webhooks + OAuth callbacks exempt. |
MaintenanceMode | Admin-toggleable 503; admins exempt |
Blacklist | IP / country / domain blacklist read from settings table (security.blacklisted_*) |
AuthLimiter | 6 attempts / 10 min per IP on register/login/lost-password (Retry-After: 600) |
AIQuotaLimiter | 50 AI generations / hour per user ID (fallback to IP) |
Idempotency | POSTs with Idempotency-Key cached for 24 h; replays return Idempotent-Replayed: true |
Open-redirect guard isSafeRedirectURL() in handlers/redirect.go rejects non-http/https destinations.
Dynamic rate-limit config (P2-16)
services/ratelimit_config.go → DynamicRateLimitConfig reads security.* keys from the settings table every 60 s. AuthLimiter and AIQuotaLimiter call SetProvider() so admins can change limits at runtime from /admin/settings → Security without restart.
Frontend Architecture (React + Vite)
Structure
apps/web/src/
├── styles/ # tokens.css (CSS custom properties), index.css
├── hooks/ # useTheme, useFeatureFlag, queries/{useLinks,useBiolinks,…}
├── lib/queryKeys.ts # Typed TanStack Query key factory (30+ resources)
├── components/
│ ├── layout/ # Sidebar, Topbar, AppLayout, AdminLayout, PageHeader, CommandPalette, FilterBar
│ ├── editor/ # CommentsPanel (the Bio page editor's block comments)
│ └── blocks/ # BlockFields — generic schema renderer (BlockFieldSpec), in the Bio page editor's Customise panel
├── pages/ # 79 route pages across 30 subdirectories
├── services/ # 36 typed API client modules (axios)
├── stories/ # Storybook stories
├── store/ # Zustand auth store
├── types/ # Shared TypeScript types
├── i18n.ts # i18next bootstrap from /api/v1/languages
├── App.tsx # Route definitions (React Router v6)
└── main.tsx # QueryClientProvider + i18n bootstrap + render
Server state — TanStack Query v5
QueryClientProvider in main.tsx with staleTime=30s, gcTime=5min, retry=1. Every list/detail page consumes a custom hook from src/hooks/queries/:
const { data, isLoading } = useLinks({ page, search });
const { mutateAsync } = useCreateLink();
Mutation hooks call queryClient.invalidateQueries({ queryKey: ['links'] }) on success. Resource-scoped invalidation cascades (mutations on a specific biolink also invalidate biolinks.detail(id)).
Design System
- Token-driven: all colors, typography, spacing, shadows, animations as CSS custom properties in
tokens.css - Theming: light/dark via
data-themeon<html>, toggled byuseThemewithlocalStoragepersistence - Brand: Studio design system — electric-lime accent (OKLCH), Bounded/Instrument Serif/Inter Tight/JetBrains Mono, cool-neutral surfaces, glass chrome. Canonical source:
studio/studio/README.md. - Components: all pages use
@csxbase/studio-reactcomponents (track 002);apps/web/src/components/ui/is gone, its last two domain components (DisplayRulesEditor,TimezonePicker) living beside the app's other domain components inapps/web/src/components/— hand-written CSS, no Tailwind/utility framework - Accessibility: WCAG AA contrast, focus-visible rings,
aria-invalid/aria-describedby,role="alert"on error spans,prefers-reduced-motionsupport - Icons: Lucide React (stroke 1.75, 20px, round caps)
- Full spec:
studio/docs/(tokens, components, interaction patterns; the olddocs/DESIGN-SYSTEM.mdis archived in.archives/removal-safe/)
Key Patterns
- Routing: React Router v6 with
ProtectedRoute/GuestRoute/AdminRouteguards - HTTP: axios with JWT injection +
X-Requested-With: XMLHttpRequest(CSRF) + response interceptor (data: null→[]) - i18n: English bundled at
locales/en.jsonand initialised synchronously;/api/v1/languagesis fetched after mount and layered over it per key (ADR-0081/0087). The language control lives in the topbar's account menu and draws nothing until the server carries a second language (ADR-0088) - Feature flags:
useFeatureFlag(FEATURE_FLAGS.key)(TanStack Query, 60s stale, false while loading and on error) backed by the authenticatedGET /api/v1/feature-flags/evaluate, which evaluates against the caller's plan (ADR-0011) - Bundling: Vite manual chunks (
react-vendor,query,i18n,dnd,icons) reduce main bundle to ~640 KB - Visual regression: Playwright (Chromium + Pixel 7), 1% pixel-diff threshold
- Storybook 8 with light/dark theme toolbar
Database Architecture (PostgreSQL 16)
Tables (61 across 44 migrations)
| Migration | Notable additions |
|---|---|
| 000001 | users, plans, links, biolinks_blocks, qr_codes, projects, domains, pixels, payments, notification_handlers, splash_pages, track_links, data, codes, redeemed_codes, taxes, user_logs, internal_notifications |
| 000002 | teams, teams_members |
| 000003 | uploads |
| 000004 | user_history_events, signatures |
| 000005 | ai_chats, ai_chat_messages, ai_images, ai_texts, ai_syntheses, ai_transcriptions + user AI columns |
| 000006 | affiliates_commissions, affiliates_withdrawals + user referral columns |
| 000007 | blog posts, pages |
| 000008 | broadcasts |
| 000009 | languages |
| 000010 | push_notifications, push_subscribers |
| 000011 | chat_assistants, ai_templates, documents, guest_payments |
| 000012 | pwas |
| 000013 | display_rules JSONB, timezone, scheduled_at/end on links + biolinks_blocks |
| 000014 | webhook_logs (gateway, external_id) UNIQUE |
| 000015 | Domain SSL state + redirect_type + verification |
| 000016 | code scheduling (is_scheduled, start/end, is_bulk) |
| 000017 | admin_logs |
| 000018 | 21 CONCURRENTLY composite indexes on (user_id, datetime) for links/qr_codes/payments/track_links + email/api_key + domains/pixels/projects |
| 000019 | idempotency_keys (24 h TTL) |
| 000020 | job_queue + status enum + SKIP LOCKED poll index |
| 000021 | email_bounces, email_unsubscribe_tokens |
| 000022 | feature_flags |
| 000023 | widen legacy VARCHAR(64) columns |
| 000024 | api_tokens (scoped, digest-only — ADR-0002) |
| 000025 | idempotency_keys NULLS NOT DISTINCT |
| 000026 | workspaces + workspace_members + workspace_id on 14 owned tables with personal-workspace backfill (ADR-0006) |
| 000027 | biolinks_blocks.version (optimistic concurrency) |
| 000028 | user_history_events.workspace_id + scope index (undo/redo session guard) |
| 000029 | referred by bigint |
| 000030 | add pwa link id |
| 000031 | grant capabilities to existing plans |
| 000032 | drop plaintext link passwords |
| 000033 | drop stale biolink gate passwords |
| 000034 | drop stale vcard and payment gate passwords |
| 000035 | attribute the last writer of a block |
| 000036 | add resource comments |
| 000037 | target a comment at a block |
| 000038 | record when a resource was last used |
| 000039 | a url has a lifecycle state |
| 000040 | a notice is sent once per resource per state |
| 000041 | an archived resource has an address of its own |
| 000042 | a stored artifact records the bytes it holds |
| 000043 | the free plan is a row that says so |
| 000044 | a heading level the page can serve |
| 000045 | the ladder has the Overview's rungs (ADR-0166) |
| 000046 | a reset code expires and a reset ends every session (ADR-0168) |
| 000047 | a broadcast is delivered once per recipient (ADR-0172) |
| 000048 | a second factor has recovery codes (ADR-0173) |
| 000049 | a second factor is on once confirmed, and asked for everywhere (ADR-0174) |
Key Design Decisions
- JSONB for settings, preferences, billing, plan_settings, display_rules (rich querying without schema churn)
- Typed schemas where structure matters (
BlockFieldSpec,BiolinkThemeSettings,settings_schema.go) — the JSONB column is hydrated into a typed Go struct on read - pgx/v5 driver for native PostgreSQL features; pool tuned for production (
MaxConns=30,MaxConnLifetime=30m) - Migrations are reversible (every
.up.sqlhas a matching.down.sql) and never run automatically by the binary; startup schema guards refuse to boot on a pre-000026/27/28 schema - Workspace tenancy (ADR-0006):
user_idstays owner-of-record + billing anchor on every row;workspace_idis the access boundary repositories filter on. Personal workspace per user backfilled,X-Workspace-IDselects, scoped tokens are pinned to their minting workspace, roles member/admin/owner - Optimistic concurrency on biolink blocks: writers send the loaded
version, updates compare-and-swap, stale saves answer 409 - Undo/redo is scoped to (user, workspace, per-tab
X-Session-ID) and single-step; unscoped writes record no history - Realtime: SSE gateway at
/api/v1/realtimewithuser:{id}/workspace:{id}channels — Redis pub/sub fan-out when configured, in-process bus otherwise
API Surface
Totals
| Surface | Count |
|---|---|
| Total routes | 416 (registered in cmd/server/main.go) |
| Handler files | 127 |
| AI tool groups | 5 (chat, images, text, synthesis, transcription) |
| Payment gateways | 22 implementations (21 registered at startup) |
| OAuth providers | 5 |
| Notification channels | 13 (Webhook, Slack, Discord, Telegram, MS Teams, Google Chat, Email, Twilio SMS/Call, WhatsApp, X, Push, Email) |
| Pixel types | 24 |
| QR code types | 28 (across 8 groups: web, basic, contact, messaging, network, location, calendar, payment, app) |
| Block types | 85 |
Machine-readable spec: shared/contracts/openapi.yaml (OpenAPI 3.1). Human-readable reference: docs/API.md.
Public Endpoints
| Endpoint | Purpose |
|---|---|
GET /l/{url} | Short-link redirect — GeoIP, cookie-based unique visitors, display-rule filter, click tracking |
GET /b/{url} | Public biolink JSON for React rendering — display-rule-filtered blocks |
POST /b/{url}/submit | Form submissions (email/phone collector) with notification dispatch |
GET /api/v1/directory | Public biolink directory (opt-in via directory_is_enabled) |
GET /api/v1/spotlight?q=… | Global search across biolinks + short links + users (authenticated) |
POST /webhook/{gateway} | Payment gateway webhooks (HMAC verified, duplicate-rejected) |
Testing
- Backend: handler test files alongside every handler (
*_test.go) — consumer-side interface mocking, no database dependencies. CI runsgo test,go vet,staticcheck. - Frontend: TypeScript
noUnusedLocalsstrict mode, Storybook for primitive states, Playwright visual regression (apps/web/tests/visual/biolink.spec.ts) with mocked API responses. - Load:
scripts/load-test.js(k6) targets/l/{shortcode}and/b/{slug}; run by hand, not by CI (seedocs/PERFORMANCE.md). - Migration lint:
.github/workflows/ci.ymljob verifies sequential numbering and matching.up.sql/.down.sqlpairs.
External Integrations
| Category | Integrations |
|---|---|
| Payment Gateways | Stripe, PayPal, Razorpay, Coinbase Commerce, Mollie, Paddle, Paddle Billing, Paystack, PayU, Mercado Pago, Midtrans, Iyzico, Flutterwave, Klarna, LemonSqueezy, MyFatoorah, Plisio, Plisio Whitelabel, Revolut, Crypto.com, YooKassa, offline payment |
| OAuth Providers | Google, Facebook, Discord, LinkedIn, Microsoft |
| Notifications | Webhook, Slack, Discord, Telegram, MS Teams, Google Chat, Email, Twilio SMS, Twilio Call, WhatsApp, X, Web Push |
| AI | OpenAI (OPENAI_API_KEY), Google Gemini (GEMINI_API_KEY), AWS Polly (AWS_POLLY_*) and Google Cloud TTS (GOOGLE_CLOUD_TTS_API_KEY) behind services/ai_router.go |
| Storage | Local FS or S3-compatible (AWS, DO Spaces, Wasabi, Vultr) via custom SigV4 |
| GeoIP | MaxMind GeoLite2 (GEOIP_DB_PATH) |
| CAPTCHA | reCAPTCHA, hCaptcha, Cloudflare Turnstile |
SMTP (RFC 8058 List-Unsubscribe headers on marketing emails) |
Multi-region readiness
The decision to defer active multi-region, its activation gates and the upgrade path are recorded in ADR-0159.
Source: docs/ARCHITECTURE.md