Skip to content
Toolkit

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

PackagePurpose
cmd/serverEntry point — 416 routes, full DI wiring, server lifecycle
internal/handlers127 HTTP handler files + tests
internal/servicesBusiness logic, external integrations
internal/repository52 pgx data-access files
internal/models40+ domain models, JSONMap, typed schemas
internal/middlewareAuth, ratelimit, CSRF, security headers, admin audit, idempotency, maintenance, blacklist, request_id, logging
internal/configEnv-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

MethodWhere
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
OAuthGoogle, 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 gatemiddleware/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_queue table (migration 000020)
  • Concurrency: 3 worker goroutines, each polling with SELECT … FOR UPDATE SKIP LOCKED LIMIT 1
  • Retries: exponential back-off (2^attempt minutes) up to max_attempts
  • Reaper: separate goroutine resets running rows 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:

  1. Subscription expiry check (hourly)
  2. Tracking data cleanup (daily, 365-day retention)
  3. User activity log cleanup (daily, 90-day retention)
  4. Expired discount code deactivation (daily)
  5. Read notification cleanup (weekly, 30-day retention)
  6. User last_activity sync (every 30 minutes)
  7. 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 — Cacher interface in internal/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 use staleTime: Infinity.

Observability (P2-1, P2-15)

  • Logging: log/slog JSON in production with request_id, user_id, method, path, status, duration on every line.
  • Request ID: custom middleware.RequestID generates a 16-hex-char ID, sets X-Request-ID response header, propagates via context.
  • Metrics: GET /metrics Prometheus text — requests_total, errors_total, uptime_seconds, goroutines, heap_alloc_bytes.
  • Readiness: GET /ready returns {status, checks: {db: ok|fail}}.
  • Admin audit: every admin POST/PUT/PATCH/DELETE persists to admin_logs (migration 000017) via middleware/admin_audit.go (fire-and-forget goroutine).

Security Middleware (P2-7, P0-7)

MiddlewareBehavior
SecurityHeadersX-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy: strict-origin-when-cross-origin
CSRFGuardRejects state-changing requests missing X-Requested-With: XMLHttpRequest. Webhooks + OAuth callbacks exempt.
MaintenanceModeAdmin-toggleable 503; admins exempt
BlacklistIP / country / domain blacklist read from settings table (security.blacklisted_*)
AuthLimiter6 attempts / 10 min per IP on register/login/lost-password (Retry-After: 600)
AIQuotaLimiter50 AI generations / hour per user ID (fallback to IP)
IdempotencyPOSTs 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-theme on <html>, toggled by useTheme with localStorage persistence
  • 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-react components (track 002); apps/web/src/components/ui/ is gone, its last two domain components (DisplayRulesEditor, TimezonePicker) living beside the app's other domain components in apps/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-motion support
  • Icons: Lucide React (stroke 1.75, 20px, round caps)
  • Full spec: studio/docs/ (tokens, components, interaction patterns; the old docs/DESIGN-SYSTEM.md is archived in .archives/removal-safe/)

Key Patterns

  • Routing: React Router v6 with ProtectedRoute / GuestRoute / AdminRoute guards
  • HTTP: axios with JWT injection + X-Requested-With: XMLHttpRequest (CSRF) + response interceptor (data: null → [])
  • i18n: English bundled at locales/en.json and initialised synchronously; /api/v1/languages is 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 authenticated GET /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)

MigrationNotable additions
000001users, 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
000002teams, teams_members
000003uploads
000004user_history_events, signatures
000005ai_chats, ai_chat_messages, ai_images, ai_texts, ai_syntheses, ai_transcriptions + user AI columns
000006affiliates_commissions, affiliates_withdrawals + user referral columns
000007blog posts, pages
000008broadcasts
000009languages
000010push_notifications, push_subscribers
000011chat_assistants, ai_templates, documents, guest_payments
000012pwas
000013display_rules JSONB, timezone, scheduled_at/end on links + biolinks_blocks
000014webhook_logs (gateway, external_id) UNIQUE
000015Domain SSL state + redirect_type + verification
000016code scheduling (is_scheduled, start/end, is_bulk)
000017admin_logs
00001821 CONCURRENTLY composite indexes on (user_id, datetime) for links/qr_codes/payments/track_links + email/api_key + domains/pixels/projects
000019idempotency_keys (24 h TTL)
000020job_queue + status enum + SKIP LOCKED poll index
000021email_bounces, email_unsubscribe_tokens
000022feature_flags
000023widen legacy VARCHAR(64) columns
000024api_tokens (scoped, digest-only — ADR-0002)
000025idempotency_keys NULLS NOT DISTINCT
000026workspaces + workspace_members + workspace_id on 14 owned tables with personal-workspace backfill (ADR-0006)
000027biolinks_blocks.version (optimistic concurrency)
000028user_history_events.workspace_id + scope index (undo/redo session guard)
000029referred by bigint
000030add pwa link id
000031grant capabilities to existing plans
000032drop plaintext link passwords
000033drop stale biolink gate passwords
000034drop stale vcard and payment gate passwords
000035attribute the last writer of a block
000036add resource comments
000037target a comment at a block
000038record when a resource was last used
000039a url has a lifecycle state
000040a notice is sent once per resource per state
000041an archived resource has an address of its own
000042a stored artifact records the bytes it holds
000043the free plan is a row that says so
000044a heading level the page can serve
000045the ladder has the Overview's rungs (ADR-0166)
000046a reset code expires and a reset ends every session (ADR-0168)
000047a broadcast is delivered once per recipient (ADR-0172)
000048a second factor has recovery codes (ADR-0173)
000049a 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.sql has 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_id stays owner-of-record + billing anchor on every row; workspace_id is the access boundary repositories filter on. Personal workspace per user backfilled, X-Workspace-ID selects, 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/realtime with user:{id} / workspace:{id} channels — Redis pub/sub fan-out when configured, in-process bus otherwise

API Surface

Totals

SurfaceCount
Total routes416 (registered in cmd/server/main.go)
Handler files127
AI tool groups5 (chat, images, text, synthesis, transcription)
Payment gateways22 implementations (21 registered at startup)
OAuth providers5
Notification channels13 (Webhook, Slack, Discord, Telegram, MS Teams, Google Chat, Email, Twilio SMS/Call, WhatsApp, X, Push, Email)
Pixel types24
QR code types28 (across 8 groups: web, basic, contact, messaging, network, location, calendar, payment, app)
Block types85

Machine-readable spec: shared/contracts/openapi.yaml (OpenAPI 3.1). Human-readable reference: docs/API.md.

Public Endpoints

EndpointPurpose
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}/submitForm submissions (email/phone collector) with notification dispatch
GET /api/v1/directoryPublic 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 runs go test, go vet, staticcheck.
  • Frontend: TypeScript noUnusedLocals strict 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 (see docs/PERFORMANCE.md).
  • Migration lint: .github/workflows/ci.yml job verifies sequential numbering and matching .up.sql/.down.sql pairs.

External Integrations

CategoryIntegrations
Payment GatewaysStripe, 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 ProvidersGoogle, Facebook, Discord, LinkedIn, Microsoft
NotificationsWebhook, Slack, Discord, Telegram, MS Teams, Google Chat, Email, Twilio SMS, Twilio Call, WhatsApp, X, Web Push
AIOpenAI (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
StorageLocal FS or S3-compatible (AWS, DO Spaces, Wasabi, Vultr) via custom SigV4
GeoIPMaxMind GeoLite2 (GEOIP_DB_PATH)
CAPTCHAreCAPTCHA, hCaptcha, Cloudflare Turnstile
EmailSMTP (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

Library