Technical Requirement Document · v1.0

CodeVault
Platform

A modern, enterprise-grade platform for generating, managing, tracking, and verifying QR codes, barcodes, and all universal encoding formats — built for scale, designed for experience.

Document Type
Technical Requirement Document
Version
1.0 — Initial Release
Status
Draft — For Review
Stack
Node.js · Next.js · React Native · PostgreSQL
01 — Executive Summary

Project Overview

CodeVault is a full-stack, multi-platform SaaS product that enables individuals, developers, and enterprises to generate, customize, manage, track, and verify every major code encoding standard — from QR codes and 1D barcodes to advanced 2D matrix formats. The platform is built with performance, scalability, and an exceptional user experience as first-class requirements.

The system is composed of four primary applications: a RESTful + WebSocket API (Node.js/TypeScript), a web portal (Next.js), a mobile app (React Native), and an enterprise back office (Next.js). All applications share a PostgreSQL database cluster and are orchestrated via a microservice-aligned monorepo.

Design Principles
  • Performance first — sub-200ms API responses for code generation; sub-50ms for verification
  • Developer-friendly — first-class API & SDK support with OpenAPI 3.1 documentation
  • Enterprise-ready — SSO, RBAC, white-labelling, audit logs, SLA tiers
  • Privacy by design — GDPR/CCPA compliant from day one

Target Audiences

👤
Individual Users / Freelancers
Generate codes for personal links, vCards, social profiles. Free tier with basic analytics.
🏢
SMBs & Agencies
Campaign-based code management, team collaboration, branded codes, and bulk generation.
🏭
Enterprises
High-volume generation, SSO/SAML, white-label, dedicated infra, SLA, API access, ERP integrations.
🛠️
Developers & Integrators
Full REST & GraphQL APIs, SDKs (JS, Python, PHP, Go), webhooks, and sandbox environments.
02 — Use Cases

Supported Use Cases

CodeVault supports an expansive range of encoding payloads and deployment scenarios across industries.

Code Type Support

Category Format Max Data Primary Use
2D MatrixQR Code (v1–v40)4,296 charsURLs, payments, authentication
2D MatrixData Matrix2,335 charsIndustrial, pharmaceutical labels
2D MatrixPDF4171,850 bytesID documents, boarding passes, legal
2D MatrixAztec Code3,067 charsTransport tickets, boarding passes
2D MatrixMaxiCode93 charsUPS/FedEx parcel tracking
1D LinearCode 128 / GS1-128Logistics, warehousing
1D LinearEAN-13 / EAN-813 digitsRetail product labelling
1D LinearUPC-A / UPC-E12 digitsNorth American retail
1D LinearCode 39 / Code 93Healthcare, military, automotive
1D LinearITF / ITF-14Shipping cartons, GS1 packaging
1D LinearCodabarBlood banks, libraries, FedEx
PostalUSPS IMb / PostNetMail sorting automation
PostalRoyal Mail 4-StateUK postal services
EmergingDotCodeHigh-speed printing, tobacco marking
EmergingHanXin Code7,827 charsChinese market, large payload

Payload / Content Types

🔗
URL & Smart Links
Dynamic redirect URLs with A/B testing, geo-routing, device detection, and UTM tagging.
👤
vCard / Contact
Full vCard 4.0 support — name, photo, phone, email, org, social handles, geo.
📄
Documents
Link to hosted PDF, DOCX, XLSX, PPTX — with access control, expiry, and download tracking.
📶
WiFi Credentials
WPA/WPA2/WEP/nopass networks. One-tap connect from mobile.
💳
Payment Codes
EMVCo QR, UPI, PayMe, Bitcoin, Ethereum addresses, PayPal.me links.
🎫
Event Tickets
Single/multi-scan tickets with expiry, check-in logging, and seat assignments.
🔐
TOTP / 2FA
Generate TOTP provisioning URIs compatible with Google Authenticator, Authy.
🗺️
Geo Location
Latitude/longitude with optional radius — opens Google Maps, Apple Maps, or Waze.
📱
App Store Links
Universal links routing iOS to App Store, Android to Play Store — from a single code.
📧
Email / SMS
Pre-filled mailto: or sms: with subject, body, recipients.
🏷️
Product / Inventory
SKU, serial, batch, expiry dates. ERP/WMS integrations for real-time stock lookups.
🎨
Social / Portfolio
Multi-link social cards (Linktree-style), portfolio pages, Spotify tracks.
📰
Plain Text / MECARD
Unformatted text or Japanese MECARD contact format.
🏥
Healthcare / HL7
Patient ID codes, medication labels with GS1 AI fields, specimen tracking.
🔑
Encoded Secrets
Encrypted payloads, password-protected access, one-time-view codes.
📡
NFC / Bluetooth
Generate codes that hand off to NFC tags or Bluetooth pairing URIs.
03 — Feature Catalogue

Core Feature Set

Code Generation Engine

  • Static Codes — payload baked in; no redirect; ideal for print permanence
  • Dynamic Codes — short-URL redirect layer; payload editable post-print without reprinting
  • Bulk Generation — CSV/Excel upload with column mapping; generate thousands in one job with ZIP download
  • Templated Generation — reusable templates for payload structure (e.g., product label schema)
  • Scheduled Expiry — codes auto-deactivate on date/time, after N scans, or by geography
  • Versioned Payloads — full history of payload changes for dynamic codes

Design & Customisation Studio

  • Colour palette control — foreground, background, gradients, transparent backgrounds
  • Custom logo / watermark embedding with configurable size and position
  • Dot shape variants — square, rounded, circle, diamond, leaf, star
  • Eye / finder pattern customisation (QR specific)
  • Frame templates (call-to-action frames: "Scan Me", "Download App", custom text)
  • Brand kit management — save org colours, fonts, and logo for team-wide consistency
  • Error correction level selector (L / M / Q / H for QR)
  • Export formats — PNG, SVG, PDF, EPS (vector), WebP
  • Resolution & DPI control for print-ready exports (300dpi+)

Analytics & Tracking

  • Scan Events — timestamp, IP (hashed for privacy), user-agent, referrer
  • Geo Analytics — country, region, city-level heatmaps via MaxMind GeoIP2
  • Device Breakdown — OS, browser, form factor (mobile/desktop/tablet)
  • Time-series Charts — hourly / daily / weekly / monthly scan trends
  • Funnel Analytics — scan → page visit → conversion tracking via UTM
  • Campaign Aggregation — roll up analytics across multiple codes in a campaign
  • Real-time Dashboard — live scan counter via WebSocket push
  • Export Reports — CSV, PDF, Excel with scheduled email delivery
  • Webhook Events — push scan events to external systems (Zapier, Slack, custom endpoints)

Verification & Authenticity

  • Signed Codes — HMAC-SHA256 or Ed25519 digital signatures embedded in payload
  • Verification API — instant signature validation endpoint (<50ms)
  • Anti-counterfeit Tokens — unique one-time tokens per physical item
  • Scan History — log of all verification events with timestamps and geo
  • Tamper Detection — alerts when identical codes scanned in geographically implausible locations
  • Certificate Chains — multi-level trust chains for B2B supply chain scenarios

Workspace & Collaboration

  • Organisations → Teams → Projects → Folders → Codes hierarchy
  • RBAC with granular permissions (Owner / Admin / Editor / Analyst / Viewer)
  • Code sharing with external collaborators (link-based, time-limited)
  • Activity feed and audit trail per workspace
  • Comments and labels on individual codes

Developer Platform

  • REST API with OpenAPI 3.1 specification + interactive Swagger UI
  • GraphQL API for flexible queries (analytics, bulk operations)
  • Official SDKs: JavaScript/TypeScript, Python, PHP, Go, Ruby, Java
  • Webhook delivery with retry, signature verification, and event logs
  • Sandbox / test mode environment with isolated data
  • API Key management with scopes, IP allowlists, and rate limits per key
  • OAuth 2.0 (Authorization Code + PKCE) for third-party integrations
04 — System Architecture

System Architecture

Client Layer
Next.js Web App (SSR/ISR)
React Native Mobile (iOS + Android)
Back Office Admin (Next.js)
Developer Portal (Next.js)
↓ HTTPS / WSS
Edge & Gateway Layer
Cloudflare CDN + WAF
API Gateway (Kong / AWS API GW)
Rate Limiter (Redis)
Short URL Resolver (Edge Function)
Application Services Layer
Auth Service (Node.js/TS)
Code Gen Service (Node.js/TS)
Analytics Service (Node.js/TS)
Scan Ingest Service (Node.js/TS)
Notification Service (Node.js/TS)
File / Asset Service (Node.js/TS)
Billing Service (Node.js/TS)
Webhook Dispatcher (BullMQ)
Data Layer
PostgreSQL (Primary + Read Replicas)
Redis (Cache + Queues + Sessions)
ClickHouse (Scan Event Analytics)
S3-Compatible Object Store
Elasticsearch (Search + Audit Logs)
Infrastructure & Observability
Kubernetes (EKS / GKE)
Prometheus + Grafana
OpenTelemetry Tracing
PagerDuty Alerting
GitHub Actions CI/CD

Monorepo Structure

codevault/
├── apps/
│   ├── api/              # Node.js + TypeScript — Express/Fastify
│   ├── web/              # Next.js 15 — User portal
│   ├── admin/            # Next.js 15 — Back office
│   ├── mobile/           # React Native + Expo
│   └── dev-portal/       # Next.js 15 — Docs + Swagger
├── packages/
│   ├── core/             # Shared business logic, types, validators
│   ├── db/               # Drizzle ORM schema + migrations
│   ├── codegen/          # Code generation engine (pure TS)
│   ├── analytics/        # Analytics data models and queries
│   ├── ui/               # Shared design system components
│   └── config/           # ESLint, TypeScript, Prettier configs
├── infra/
│   ├── k8s/              # Kubernetes manifests
│   ├── terraform/        # IaC for AWS/GCP
│   └── docker/           # Dockerfiles per service
└── turbo.json            # Turborepo pipeline config

Key Architectural Decisions

DecisionChoiceRationale
API FrameworkFastify3x faster than Express; schema-first validation with Zod; excellent TypeScript support
ORMDrizzle ORMType-safe SQL; zero runtime overhead; excellent migration tooling; PostgreSQL native
Analytics StoreClickHouseColumnar store handles billions of scan events; sub-second aggregation queries
Queue SystemBullMQ + RedisReliable job queues for bulk gen, webhook delivery, report emails
Short URLsEdge FunctionsCloudflare Workers resolve redirects at edge (<5ms globally) without hitting origin
Caching StrategyRedis + CDNL1: Redis for hot code data; L2: Cloudflare for static assets and code images
Real-timeSocket.ioWebSocket push for live analytics dashboard and scan notifications
SearchElasticsearchFull-text search across codes, campaigns, audit logs; fuzzy matching for back office
05 — Database Design

PostgreSQL Schema

Core entity relationships — all tables use UUID primary keys, soft deletes (deleted_at), and created_at / updated_at timestamps.

organisations
idUUIDPK, default gen_random_uuid()
nameVARCHAR(255)Organisation display name
slugVARCHAR(100)Unique URL slug, indexed
plan_idUUIDFK → billing_plans
sso_configJSONBSAML/OIDC config for enterprise SSO
brand_kitJSONBColours, fonts, logo URL, defaults
settingsJSONBFeature flags, limits, preferences
users
idUUIDPK
org_idUUIDFK → organisations (nullable for personal accounts)
emailVARCHAR(320)Unique, indexed, verified flag
password_hashVARCHAR(255)Argon2id, nullable (OAuth users)
roleENUMowner | admin | editor | analyst | viewer
mfa_secretVARCHAR(255)TOTP secret, encrypted at rest
oauth_providersJSONBArray of {provider, provider_id, access_token}
preferencesJSONBUI preferences, notification settings
codes
idUUIDPK
short_idVARCHAR(12)Unique short identifier for redirect URL, indexed
org_idUUIDFK → organisations
project_idUUIDFK → projects
created_byUUIDFK → users
code_typeENUMqr | code128 | ean13 | pdf417 | datamatrix | aztec | ...
payload_typeENUMurl | vcard | wifi | text | email | geo | payment | ...
is_dynamicBOOLEANTrue = redirect-based; False = static payload
destination_urlTEXTCurrent active redirect target
payloadJSONBStructured payload data (vCard fields, WiFi params, etc.)
designJSONBVisual customisation options
image_urlsJSONB{png, svg, pdf} S3 asset paths
signatureVARCHAR(512)Ed25519 signature for authenticity verification
scan_limitINTEGERNullable; deactivates after N scans
expires_atTIMESTAMPTZNullable; auto-deactivates
geo_restrictionJSONBAllowed country codes list
password_hashVARCHAR(255)Nullable; password-protected codes
statusENUMactive | paused | expired | archived
total_scansBIGINTDenormalised counter, updated atomically
tagsTEXT[]Searchable tags array, GIN indexed
scan_events (also mirrored to ClickHouse)
idUUIDPK, partitioned by month (range)
code_idUUIDFK → codes, indexed
scanned_atTIMESTAMPTZEvent timestamp, partition key
ip_hashVARCHAR(64)SHA-256 of IP + daily salt (GDPR)
country_codeCHAR(2)ISO 3166-1 alpha-2
regionVARCHAR(100)State/province
cityVARCHAR(100)City name
device_typeENUMmobile | desktop | tablet | bot
osVARCHAR(50)iOS, Android, Windows, macOS, Linux
browserVARCHAR(50)Chrome, Safari, Firefox, etc.
referrerTEXTHTTP Referer header value
is_uniqueBOOLEANFirst scan from this ip_hash per code
verifiedBOOLEANSignature verification result
Also required: projects · campaigns · templates · api_keys · webhooks · audit_logs · billing_plans · subscriptions · bulk_jobs · folders
Full schema in /packages/db/schema.ts — see Drizzle ORM definitions

PostgreSQL Indexing Strategy

-- Hot path: dynamic code redirect resolution
CREATE INDEX idx_codes_short_id ON codes(short_id) WHERE deleted_at IS NULL;
CREATE INDEX idx_codes_status ON codes(status, expires_at);

-- Analytics queries
CREATE INDEX idx_scan_events_code_scanned ON scan_events(code_id, scanned_at DESC);
CREATE INDEX idx_scan_events_country ON scan_events(country_code, scanned_at DESC);

-- Full-text & tag search
CREATE INDEX idx_codes_tags ON codes USING GIN(tags);
CREATE INDEX idx_codes_search ON codes USING GIN(
  to_tsvector('english', name || ' ' || coalesce(description,''))
);

-- Partitioning for scan_events (by month)
CREATE TABLE scan_events PARTITION BY RANGE (scanned_at);
06 — API Design

API Design

All API routes are prefixed with /api/v1. Authentication via Bearer {JWT} or X-API-Key: {key} header. Responses follow JSON:API-inspired structure.

Authentication

POST/auth/register
Create new user account. Returns JWT pair.
POST/auth/login
Authenticate with email + password or OAuth token. Returns access_token (15m) + refresh_token (30d).
POST/auth/refresh
Rotate refresh token and issue new access token.
POST/auth/mfa/verify
Validate TOTP code during MFA login step.
GET/auth/sso/:orgSlug
Initiate enterprise SSO / SAML flow for organisation.

Code Management

POST/codes
Generate a new code. Body: code_type, payload_type, payload, design, is_dynamic, expiry options.
GET/codes
List codes with filtering (type, status, tags, project), pagination, full-text search.
GET/codes/:id
Fetch single code with design, payload, analytics summary, and image URLs.
PATCH/codes/:id
Update dynamic code payload, design, status, or expiry. Triggers image regeneration job.
DELETE/codes/:id
Soft delete. Code becomes inactive; analytics retained.
POST/codes/bulk
Start a bulk generation job. Accepts CSV or JSON array. Returns job_id for polling.
GET/codes/:id/download
Download code image. Query params: format=png|svg|pdf|eps, dpi=72|150|300.

Analytics

GET/codes/:id/analytics
Time-series scan data. Params: from, to, granularity=hour|day|week.
GET/codes/:id/analytics/geo
Geographic breakdown — country, region, city with scan counts.
GET/codes/:id/analytics/devices
Device, OS, browser breakdown with percentages.
GET/campaigns/:id/analytics
Aggregated analytics across all codes in a campaign.

Verification

POST/verify
Verify a scanned code payload. Body: raw_payload string. Returns: valid bool, code metadata, signature status. <50ms SLA.
GET/verify/:shortId/history
Scan history for a verification token with geo and timestamp info.

Short URL Redirect (Edge)

GETr.codevault.io/:shortId
Cloudflare Worker — resolves destination, logs scan event async, redirects 301/302. <10ms globally.
07 — Backend

Node.js / TypeScript API

Technology Stack

LayerTechnologyPurpose
FrameworkFastify 5HTTP server; plugin architecture; schema-validated routes
LanguageTypeScript 5.5Strict mode; project references for monorepo
ORMDrizzle ORMType-safe SQL; migrations; PostgreSQL dialects
ValidationZodRuntime schema validation; OpenAPI schema gen
AuthJose (JWT)RS256 JWTs; PKCE OAuth; Passport.js strategies
QueueBullMQRedis-backed; retries; priority; delayed jobs
CacheioredisRedis client; cluster support; pipelines
MailerResend + React EmailTransactional emails with typed templates
StorageAWS S3 / R2Code images, document uploads, exports
LoggingPinoStructured JSON logging; log levels; request ids
TestingVitest + SupertestUnit + integration tests; Istanbul coverage

Code Generation Engine

The @codevault/codegen package wraps best-in-class generation libraries into a unified, typed interface:

import { generateCode } from '@codevault/codegen';

const result = await generateCode({
  type: 'qr',
  payload: { type: 'url', value: 'https://example.com/product/123' },
  design: {
    foreground: '#1a1d27',
    background: '#ffffff',
    dotShape: 'rounded',
    eyeShape: 'square',
    logo: { url: 'https://cdn.../logo.png', size: 0.25 },
    errorCorrection: 'H',
  },
  outputs: ['png', 'svg', 'pdf'],
  dpi: 300,
  signature: { sign: true, keyId: 'key_abc123' },
});

// result.images: { png: Buffer, svg: string, pdf: Buffer }
// result.signature: 'ed25519:abc...xyz'
// result.shortId: 'x7k2mQ'

Libraries Used Internally

  • qrcode — QR code generation (v1–v40, all error correction levels)
  • bwip-js — All 1D barcode formats + PDF417, DataMatrix, Aztec
  • sharp — High-performance image processing; logo compositing; format conversion
  • PDFKit — PDF output with vector QR embedding
  • jsrsasign / @noble/ed25519 — Code signing and verification

Performance Targets

OperationP50 TargetP99 Target
Single code generation (PNG + SVG)<120ms<400ms
Dynamic code redirect (Cloudflare edge)<5ms<15ms
Verification API<20ms<50ms
Analytics query (7-day, single code)<80ms<200ms
Analytics query (30-day, campaign)<300ms<800ms
Bulk generation (1,000 codes)<45s (async job)<120s
List /codes (first page)<40ms<100ms
08 — Frontend

Next.js Web Application

Technology Stack

  • Next.js 15 (App Router, React 19, Server Components, Server Actions)
  • TailwindCSS 4 with custom design system tokens
  • shadcn/ui + custom component library (@codevault/ui)
  • TanStack Query v5 — server state management, optimistic updates, infinite scroll
  • Zustand — client state (design studio, UI state)
  • React Hook Form + Zod — form validation (shared schemas with API)
  • Recharts — analytics charts (line, bar, pie, geo choropleth)
  • Framer Motion — animations, transitions, drag interactions
  • i18next — internationalisation (en, fr, es, de, ja, zh, ar)

Key Pages & Modules

🏠
Dashboard
At-a-glance: total scans today, top performing codes, real-time scan feed, quick-create widget.
🎨
Code Studio
Full-featured visual editor for QR/barcode design. Live preview canvas with instant re-render on every change.
📁
Code Library
Grid/list view, filters, bulk actions (delete, pause, export), drag-to-folder organisation.
📊
Analytics Hub
Per-code and per-campaign analytics with world heatmap, time-series, device charts.
Bulk Generator
Upload CSV → map columns → preview → generate → download ZIP. Progress bar with live job polling.
🔍
Verifier
Upload or paste a code image/raw payload; show verification result, signature status, scan history.
🔗
Campaigns
Group codes into campaigns; add UTM parameters; compare performance across codes.
🛠️
Developer API
API key management, webhook configuration, SDK download, live API explorer.
👥
Team Settings
Invite members, assign roles, manage SSO, brand kit, billing, and usage limits.

Rendering Strategy

PageStrategyReason
Landing / MarketingSSGMaximum speed, SEO, CDN-cached
Blog / DocsISR (60s)Content updates without redeploy
Dashboard / AnalyticsSSR + ClientAuth-gated, fresh data, CSR for real-time
Code StudioCSRHeavy canvas interactions; no SEO needed
Public verifier pageSSRDynamic result; sharable with OG metadata
09 — Mobile

React Native Mobile App

Technology Stack

  • React Native 0.76 with Expo SDK 52 (Managed → Bare workflow for camera access)
  • Expo Router v4 — file-based routing, deep linking, universal links
  • React Native Reanimated 3 — 60/120fps animations on UI thread
  • React Native Vision Camera — high-performance camera with QR/barcode scanning frame processor
  • MLKit Vision (iOS/Android) — on-device ML for ultra-fast code detection
  • Expo SecureStore — biometric-protected token storage (keychain/keystore)
  • TanStack Query — shared API layer (same hooks as web)
  • MMKV — fast synchronous storage for cached data
  • react-native-svg — render SVG code images natively

Core Mobile Features

📷
Universal Scanner
Scan any code type in real-time. Auto-detects format. Shows decoded payload, verification status, and action buttons.
Quick Generate
Create codes on the go — URL, WiFi, vCard, text — with basic customisation and instant share sheet.
📲
Offline Mode
Scan and verify cached codes offline. Queue events for sync when connectivity restored.
📊
Mobile Analytics
Sparkline charts, top codes this week, real-time scan counter with push notifications.
🎫
Event Check-in Mode
Rapid-fire ticket scanning for events. Visual pass/fail feedback, haptic response, audible chime.
🔐
Biometric Auth
Face ID / Touch ID / Fingerprint login. PIN fallback. Auto-lock after configurable idle period.
📤
Share & Export
Download codes to Camera Roll or share via native share sheet. AirDrop support on iOS.
🔔
Push Notifications
Scan milestones, code expiry warnings, team activity, bulk job completion alerts.

Scanner Architecture

// Frame Processor runs on the camera thread (JSI, no bridge)
const frameProcessor = useFrameProcessor((frame) => {
  'worklet';
  const barcodes = scanBarcodes(frame, [
    BarcodeFormat.QR_CODE,
    BarcodeFormat.CODE_128,
    BarcodeFormat.EAN_13,
    BarcodeFormat.DATA_MATRIX,
    BarcodeFormat.PDF_417,
    BarcodeFormat.AZTEC,
  ]);
  if (barcodes.length > 0) {
    runOnJS(onBarcodeDetected)(barcodes[0]);
  }
}, []);

// Verification happens locally first (Ed25519), 
// then syncs event to API async
10 — Back Office

Enterprise Back Office (Admin Portal)

A separate Next.js application deployed at admin.codevault.io, accessible only to CodeVault staff and designated enterprise administrators. Built with the same UI library but with a distinct layout and elevated permissions model.

Platform Admin Capabilities

👥
User Management
Search, impersonate (with audit), suspend, reset passwords, force MFA, view login history and sessions.
🏢
Organisation Management
Create, configure, and manage orgs. Override plan limits, configure SSO, manage brand kits, view usage.
💰
Billing & Subscriptions
View invoices, adjust plan, apply coupons, manage enterprise contracts, usage overage billing.
📈
Platform Analytics
Total codes generated per day, scan volume globally, API usage heatmap, top customers by volume.
🔍
Audit Log Viewer
Searchable, filterable audit trail of all user and admin actions. Exportable for compliance.
🚦
Feature Flags
Toggle features per org or globally. Gradual rollouts. A/B test new features for cohorts.
🔔
Broadcast Notifications
Send in-app or email announcements to all users, selected plans, or specific organisations.
⚙️
System Health
Live queue depth, worker status, Redis memory, DB connections, error rate dashboard.
🤝
Enterprise Onboarding
White-label configuration (custom domain, logo, colours), SLA setup, dedicated support assignment.

Enterprise Features (per org)

  • Custom domain — white-label redirect domain (e.g., qr.acme.com)
  • White-label portal — custom branding on web and mobile
  • SAML 2.0 / OIDC SSO — Okta, Azure AD, Google Workspace, Ping Identity
  • SCIM 2.0 provisioning — auto user/group sync from IdP
  • Dedicated infrastructure — isolated DB schema or dedicated cluster option
  • SLA tiers — 99.9% (Business), 99.95% (Enterprise), 99.99% (Enterprise+)
  • Advanced RBAC — custom roles with granular permission matrices
  • ERP/WMS integrations — SAP, Oracle, Microsoft Dynamics connectors
  • Priority support — dedicated Slack channel, 4hr response SLA
  • Compliance exports — SOC 2 reports, GDPR data portability, DPA agreements
11 — Security

Security Architecture

Authentication & Authorisation

  • Passwords hashed with Argon2id (m=65536, t=3, p=4)
  • JWTs signed with RS256; access token 15min TTL; refresh token 30d; stored in httpOnly cookies
  • TOTP MFA via RFC 6238; backup codes (10x single-use, AES-256 encrypted)
  • OAuth 2.0 with PKCE for Google, GitHub, Microsoft, Apple
  • SAML 2.0 and OIDC for enterprise SSO
  • Session revocation list in Redis (logout invalidates token family)

API Security

  • Rate limiting per IP and per API key (sliding window algorithm in Redis)
  • API keys scoped to specific operations (read-only, write, admin)
  • Webhook payloads signed with HMAC-SHA256 (header: X-CodeVault-Signature)
  • CORS with explicit allowlist; CSRF protection on stateful routes
  • Request ID propagation for distributed tracing
  • SQL injection protection via Drizzle ORM parameterised queries exclusively
  • File upload scanning with ClamAV before S3 storage

Infrastructure Security

  • All traffic TLS 1.3+ via Cloudflare
  • Secrets managed via HashiCorp Vault or AWS Secrets Manager
  • Database encryption at rest (AES-256); encrypted backups to separate AWS region
  • VPC private networking; no public DB endpoints
  • Kubernetes NetworkPolicies: zero-trust pod-to-pod communication
  • Container image scanning (Trivy) in CI pipeline; no root containers
  • WAF rules blocking OWASP Top 10 attack patterns
  • DDoS protection via Cloudflare Magic Transit
Compliance Requirements
GDPR (EU), CCPA (California), SOC 2 Type II, ISO 27001, HIPAA-ready (healthcare tier), PCI-DSS Level 3 (payment QR flows). Annual penetration testing by certified third-party vendor.
12 — Performance

Performance Engineering

Code Generation Optimisations

  • Worker threads — image processing offloaded to Node.js worker thread pool (sharp is CPU-bound)
  • Result caching — identical payload + design combinations cache-hit from Redis (TTL 1hr)
  • Pre-generated assets — common sizes and formats generated eagerly and stored in S3
  • Streaming responses — large export files stream to S3 without buffering in memory

Database Performance

  • PgBouncer connection pooler (transaction mode) — 100x connection reuse
  • Read replicas for all analytics and list queries (writes to primary only)
  • Table partitioning on scan_events by month — query pruning
  • Materialised views for pre-aggregated analytics (refreshed every 5 min)
  • ClickHouse for high-cardinality analytics (billions of rows, sub-second aggregation)
  • Autovacuum tuning; pg_partman for automatic partition management

Frontend Performance

  • Next.js Partial Pre-rendering (PPR) for shell + streamed content
  • React Server Components reduce client bundle by ~40%
  • Code splitting per route + dynamic imports for heavy components (studio, analytics charts)
  • Images served as WebP via Next.js Image with blur placeholders
  • Bundle analysis in CI (bundlemon); budget alerts on regression
  • Target: LCP <1.2s, FID <50ms, CLS <0.05 (Core Web Vitals)

Scalability Design

  • Stateless API services — horizontal scaling via Kubernetes HPA
  • Scan ingest via write-optimised queue (BullMQ) — decoupled from redirect latency
  • ClickHouse cluster with 3+ shards — linear analytical throughput scaling
  • Multi-region deployment with latency-based DNS routing (Route 53)
  • Designed for 10M+ active codes and 1B+ scan events/year
13 — Infrastructure

Infrastructure & DevOps

Cloud Architecture

ComponentServiceSizing (start)
Kubernetes ClusterAWS EKS3x m7g.xlarge nodes, auto-scaling to 20
PostgreSQLAWS RDS Aurora PostgreSQLdb.r7g.large primary + 2 read replicas
RedisAWS ElastiCache (Valkey)cache.r7g.large, cluster mode
ClickHouseClickHouse Cloud / Self-hosted3-node cluster, 500GB NVMe
Object StorageAWS S3 / Cloudflare R2Unlimited; R2 for zero-egress cost
CDN / EdgeCloudflareEnterprise plan; Workers for redirect
SearchElastic Cloud2-node, hot-warm architecture
SecretsAWS Secrets Manager
EmailResend + SES fallback

CI/CD Pipeline

push → GitHub Actions:
  ├── lint (ESLint, Prettier, tsc --noEmit)
  ├── test (Vitest unit + integration, coverage ≥80%)
  ├── security scan (Trivy, npm audit, Semgrep)
  ├── build (Turborepo cache-aware parallel build)
  ├── docker build + push (ECR)
  ├── bundlemon (frontend budget check)
  └── deploy:
      ├── staging (auto, on main branch)
      └── production (manual approval gate)

Observability Stack

  • Metrics — Prometheus scraping all services; Grafana dashboards (golden signals + custom)
  • Tracing — OpenTelemetry → Grafana Tempo (distributed traces across all services)
  • Logging — Pino JSON logs → Loki → Grafana (correlated with traces via trace ID)
  • Alerting — PagerDuty integration; on-call rotation; runbook links in alerts
  • Uptime — Better Uptime for external monitoring; status page at status.codevault.io
  • Error Tracking — Sentry (API + Web + Mobile) with release tracking and performance profiling
14 — Integrations

Third-Party Integrations

Zapier & Make
Trigger code generation, get scan events, update payloads — no-code automation for 5,000+ apps.
💬
Slack
Scan milestone notifications, bulk job completion, team activity digests in your Slack channels.
📊
Google Analytics 4
Forward scan events to GA4 as custom events. Full UTM parameter passthrough.
📬
Mailchimp / HubSpot
Tag and segment contacts who scan specific codes. Trigger email automations on scan events.
🛒
Shopify / WooCommerce
Auto-generate product codes from your store catalogue. Sync inventory QR labels.
📦
SAP / Oracle ERP
Enterprise connector for bulk label generation tied to inventory, POs, and shipment records.
💳
Stripe
Subscription billing, usage-based metering, invoice management, trial management.
📱
Twilio
SMS scan alerts, OTP via SMS, two-way scan notification campaigns.
🔗
n8n (self-hosted)
Enterprise self-hosted automation with full API access for complex workflows.
📐
Figma Plugin
Generate and insert codes directly into Figma designs from within the design tool.
🖨️
Label Printers
Direct print integration with Zebra (ZPL), DYMO, and Brother via print driver API.
☁️
Google Drive / Dropbox
Import CSV files for bulk generation; export code ZIPs directly to cloud storage.
15 — Roadmap

Development Roadmap

Phase 1 — Months 1–3
Foundation & Core MVP
Auth system (email, Google, GitHub OAuth), QR + Code128 + EAN13 generation, basic design studio (colours, logo), static + dynamic codes, scan analytics (basic), web portal, PostgreSQL schema, API v1 skeleton, CI/CD pipeline, staging environment.
Phase 2 — Months 4–6
Full Format Support & Analytics
All 15+ code format support, advanced design studio (dot shapes, eye shapes, frames), ClickHouse analytics integration, geo heatmap, device breakdown, bulk generation (CSV), PDF/SVG/EPS export, React Native mobile app (scanner + basic generate), webhook system, API key management.
Phase 3 — Months 7–9
Enterprise & Verification
SAML SSO + SCIM, RBAC with custom roles, code signing + verification API, Back office admin portal, Stripe billing integration, white-label custom domains, MFA (TOTP), audit logs, campaign management, advanced mobile features (check-in mode, offline), Zapier integration.
Phase 4 — Months 10–12
Developer Platform & Scale
GraphQL API, SDKs (JS, Python, Go), interactive developer portal, Figma plugin, ERP connectors, label printer integration, multi-region deployment, SOC 2 audit, performance benchmarks, advanced feature flags, A/B testing for dynamic codes, anti-counterfeit token system.
Phase 5 — Year 2+
AI & Advanced Intelligence
AI-powered design suggestions (generate on-brand QR from brand description), predictive scan analytics, anomaly detection (counterfeit alert ML), smart code auto-routing (geo + time-aware destinations), NFC companion integration, blockchain-anchored verification chain, computer vision SDK for embedded scanner in third-party apps.

Pricing Model

PlanPriceCodesScans/moKey Features
Free$05 dynamic500QR only, basic design, 30-day analytics
Starter$12/mo50 dynamic10,000All formats, full analytics, custom logo, 2 users
Pro$39/mo500 dynamic100,000Bulk gen, campaigns, webhooks, API access, 10 users
Business$149/moUnlimited1,000,000SSO, custom domain, white-label, 50 users, priority support
EnterpriseCustomUnlimitedUnlimitedDedicated infra, SLA, SCIM, ERP, dedicated support
Next Steps
Finalise stack choices with engineering team → Set up monorepo with Turborepo → Provision staging environment → Sprint planning for Phase 1 → Design system kick-off → API contract review with OpenAPI spec draft.