Technical Documentation Visit the platform

Technical documentation · v1.0

A collaborative archive for the history of fashion.

Trama Archive is an independent, encyclopedic platform where a community catalogs historical garments, brands and their labels. It is built API-first: a Go GraphQL backend fully decoupled from a Next.js client, so new clients can be added without touching business logic.

Designed and built end-to-end by Rocco Ferrari · architecture, backend, frontend and infrastructure · GitHub ↗

API-firstSingle GraphQL endpoint
HexagonalModular monolith in Go
Zero inboundOrigin reachable only via tunnel
IT · ENBilingual interface

What the platform is — and is not

Trama is an archive, not a shop. The system does not process payments, carts, logistics or shipping. The current release focuses entirely on cataloging and community:

  • Advanced search and in-depth consultation of garment metadata.
  • Collection and moderation of user-generated content (UGC).
  • Community curation of garments, brand histories and brand label archives.

There is no monetization logic: the goal is data quality, indexing and user experience.

Key decisions

The trade-offs that shaped the system, and why.

Modular monolith over microservices

One deployable Go binary keeps operations trivial for a single maintainer, while hexagonal modules with port-only dependencies keep a future split cheap.

PostgreSQL search before Elasticsearch

Weighted full-text plus trigram similarity covers current volume without a 1–2 GB JVM. Elasticsearch is already implemented behind the same port and switches on with one variable.

Tunnel instead of open ports

An outbound-only Cloudflare Tunnel hides the origin, removes port forwarding and dynamic DNS, and puts WAF and DDoS protection in front of a self-hosted server.

Outbox for consistency

Approvals write an event in the same transaction instead of calling the search engine directly, so a network failure can never leave the index and database out of sync.

Direct-to-storage uploads

Browsers compress images to WebP and upload them to R2 with presigned URLs, so media never consumes backend bandwidth and egress stays free.

Cache by content, not by visit

Anonymous SSR queries share the Next.js Data Cache and are invalidated by a backend webhook, so load scales with content changes rather than traffic.

02

Product & Use Cases

The main interaction flows, from passive discovery to contribution and moderation.

Discovery

A trending carousel and a "featured brands" list ranked by real visits in Redis with time decay, plus a grid of the latest approved items.

Catalog search

Typo-tolerant full-text search with a filter drawer for category, gender, designer, SKU and taxonomies (color, material, fit, decade). Empty states suggest clearing filters or contributing the missing item.

Item page

Gallery, technical sheet, a modular wiki, contributor list, market value chart, favorites and a report flag. Authenticated users can suggest edits to any part.

Brand label archive

Each brand has a dated archive of its sewn-in labels, filterable by decade or free year range (kept in the URL so filtered views are shareable) to help date garments.

User dashboard

Account & security, a tracker of submitted proposals and reports, notification preferences and GDPR account deletion with anonymization.

Back-office

A unified moderation queue, side-by-side diff view for edit proposals, taxonomy merging, permanent deletion, user management and report handling.

Contribution lifecycle

Every new item or edit follows the same path from the guided wizard to the public catalog.

  1. BrandPick an existing brand via autocomplete (or propose a new one).
  2. PhotosImages are compressed to WebP in the browser before upload.
  3. AI pre-fillGemini suggests name, category, gender, season and designer; the user confirms or overrides.
  4. Metadata & wikiOptional taxonomies and a history built from titled sections, stored as structured JSON.
  5. ModerationSaved as pending; admins approve, request changes or reject with written feedback.
  6. PublicationAn outbox event updates the search index and the public page cache is revalidated.
Trust Score. Moderation outcomes adjust a contributor's reliability score: new approved items and brands earn more than approved edits or labels, while rejected items lose points. Reports never change the score.

Trust & Safety

Authenticated users can report an approved item or label (counterfeit, wrong information, inappropriate content) with a description and an optional evidence link. Reports reach admins on every channel; resolving one may apply a 24-hour timeout or a permanent ban to the content's author. Submission is rate-limited and a user can only keep one open report per target.

Localization

The interface is available in Italian and English on the same URLs. The language is stored in a technical cookie (first visit follows the browser's Accept-Language), every UI string comes from typed dictionaries, and backend errors are translated per request. User content and taxonomy names are never translated.

03

Infrastructure & Network

Production runs on a single, fully containerized self-hosted server to keep costs low during validation, with a clear path to cloud hosting. The origin accepts no inbound connections from the Internet: all public traffic enters through Cloudflare.

Request path from the browser through Cloudflare and the tunnel to Traefik, the Next.js frontend and Go backend, isolated data stores and external services self-hosted server · docker compose public network internal network · no published ports external services tunnel Browser visitor · contributor Cloudflare edge DNS · WAF · DDoS TLS · rate limiting cloudflared outbound-only tunnel Traefik v3 edge router · TLS Next.js frontend SSR · Data Cache Go backend GraphQL API PostgreSQL source of truth Redis cache · trends Elasticsearch optional Cloudflare R2 images · CDN Gemini API AI archivist eBay Browse market prices SMTP email
Figure 1 Request path. The tunnel is opened from inside the server, so no ports are forwarded. Browsers upload images straight to R2 through short-lived presigned URLs signed by the backend.
LayerTechnologyRole
EdgeCloudflareSingle public entry point. Proxied DNS records hide the origin; managed WAF, DDoS mitigation, HTTPS redirect, TLS 1.2+ and an edge rate-limit rule on the API.
TunnelcloudflaredOpens an outbound connection to Cloudflare and forwards public traffic to Traefik. No port forwarding, no dynamic DNS, works behind CGNAT.
RouterTraefik v3Routes by Docker labels and terminates TLS with Let's Encrypt certificates obtained through the DNS-01 challenge (end-to-end Full (strict) TLS).
Public networkDocker bridgeHosts the Next.js frontend and the Go backend, the only services Traefik can reach.
Internal networkDocker bridgeIsolates PostgreSQL, Redis and the optional Elasticsearch. They publish no ports and only the backend talks to them.

Operations

  • Resilient start-up: the backend retries its database and cache connections, then applies idempotent SQL migrations.
  • Health: /healthz (liveness, never checks dependencies) and /readyz (readiness: PostgreSQL is critical, Redis only degrades the status).
  • Graceful shutdown: on SIGTERM the server stops accepting requests, stops background workers and drains the worker pool.
  • Observability: structured JSON logs with request IDs and Prometheus metrics on an internal-only port; central collection and alerting are planned off-server.
  • Backups: the database and the image bucket are backed up to off-site storage on a schedule with rotation, and a weekly job restores the latest dump into a throwaway container to prove it is usable.
  • Infrastructure as code: tunnel, DNS, zone settings and access policies are versioned in Terraform.
  • Configuration: every Compose file is environment-agnostic; adapters are selected through validated environment variables, and an unknown value stops start-up instead of silently falling back.
Cloud migration, zero rewrite. Once traffic grows, the stack moves to a professional cloud host. Elasticsearch is already implemented behind the SearchRepository port and is enabled by switching one environment variable — no business logic changes.

04

Technology Stack

Frontend

Framework
Next.js 16 (App Router), React 19
Language
TypeScript, types generated from the GraphQL schema
Styling
Tailwind CSS 4
Client state
Zustand 5 (slice pattern)
Server state
urql with document cache
Libraries
recharts, browser-image-compression, lucide-react
Testing
Jest, React Testing Library

Backend

Language
Go 1.26
API
GraphQL (graphql-go), single POST endpoint
Drivers
pgx/v5, go-redis/v9
Security
golang-jwt/v5, bcrypt
Testing
go test, testify, race detector

Infrastructure

Containers
Docker, Docker Compose
Edge
Cloudflare, Cloudflare Tunnel, Traefik v3
Data
PostgreSQL 15, Redis
Media
Cloudflare R2 (aws-sdk-go-v2)
AI
Google Gemini 3.6 Flash

05

Data & Storage

PostgreSQL 15 is the single source of truth, chosen for referential integrity and ACID guarantees. Schema migrations run at every start-up in a fixed order and are written to be idempotent.

Users & access

users user_preferences user_tokens

Catalog & taxonomies

brands brand_tags items item_images taxonomies item_taxonomies

Market

item_price_history

UGC & collections

proposed_edits contributors boards favorites

Infrastructure & trust

reports notifications outbox_events

  • Full-text search: a weighted generated search_vector (name, designer, wiki) combined with pg_trgm similarity, so a typo like margela still finds Margiela. GIN indexes keep all match conditions fast.
  • Edit proposals: suggested changes are stored as JSON in proposed_edits and applied partially on approval, so the public record is never touched before review.
  • Taxonomy merge: redundant tags are merged into a master tag in one transaction; affected items are re-indexed through the outbox.
  • Soft delete: account deletion anonymizes username and email while keeping historical contributions intact.

Redis

  • Cache for item details and the brand index, invalidated on every change.
  • Ephemeral store for pending registrations, brute-force counters and market cooldowns.
  • Trending items and brands in Sorted Sets; a daily Lua script multiplies scores by 0.85 and drops low scores.
  • View de-duplication: one count per visitor per day; guests are identified only by a salted, truncated hash of their IP, which is never stored in clear.
  • Without Redis, the system falls back to a no-op cache and an in-memory store.

Cloudflare R2

  • Presigned uploads valid for five minutes and restricted to images, so files never transit through the backend.
  • Bucket CORS allows uploads only from the platform's own origins.
  • Orphan cleanup: replaced, rejected or deleted images are removed in the background.
  • Global delivery through Cloudflare's CDN with zero egress costs.

06

Frontend: Presentation & Interaction

The web client keeps server state (GraphQL cache) strictly apart from client state (Zustand), and organizes code by business domain with Feature-Sliced Design.

Frontend layers: root layout shell, App Router areas, feature-sliced modules and the shared state and network layer talking to the Go API Root layout · application shell Header · Navbar · Footer · AuthModal · ToastFactory · CookieBanner · OfflineBanner · I18nProvider Public area Home · Catalog · Item · Brands · Labels · Favorites User area Contribution wizard · Edit proposals · Profile Admin area Moderation queue · Reviews · Reports modules/ · feature-sliced design auth catalog brands contribution moderation profile notifications reports useAppStore Zustand · 3 slices i18n typed it / en dictionaries Typed documents GraphQL Codegen graphqlClient urql · interceptor Go API GraphQL
Figure 2 Frontend layers. Route areas compose feature modules, which reach the network and global state only through the shared layer.

Architecture

  • Rendering: pages are server-rendered on every request, but catalog data is read anonymously through the Next.js Data Cache, so the backend receives one query per content change instead of one per visit. The backend invalidates the cache through an authenticated revalidation webhook whenever content is approved, edited or deleted.
  • Container / presentational split: Server Components fetch data without shipping JavaScript; Client Components sit at the leaves for modals, state and interactivity.
  • Global state: three Zustand slices — AuthSlice (identity and role, never the token), UIPreferencesSlice (modal visibility, cookie consent, unread badge) and ToastSlice (auto-dismissed feedback).
  • Network client: a single urql client sends the HttpOnly session cookie, aborts requests after 10 seconds (60 for AI analysis), blocks mutations while offline and downgrades the user to guest when the session expires.
  • Type safety: the backend exports its schema and GraphQL Code Generator turns every document into a typed node.

Mobile-first UX

  • Two-column grids on phones, bottom-sheet edit modals, touch targets of at least 40px and safe-area aware overlays.
  • Swipe gestures on carousel and gallery; image reordering uses explicit cover/arrow controls instead of drag & drop.
  • Light and dark themes following prefers-color-scheme; pinch-zoom stays available for accessibility.
  • Optimistic UI with silent rollback, skeleton screens instead of spinners, and progressive image loading to avoid layout shift.

07

Backend: Core Logic & Data Layer

The server is a modular monolith in Go, structured with the hexagonal (ports & adapters) pattern. Business rules depend only on interfaces; the concrete adapter for each port is chosen at start-up from environment variables.

Hexagonal backend: primary adapters on the left drive the core domain modules through ports; secondary adapters on the right implement those ports primary adapters · driving secondary adapters · driven ports · go interfaces SearchRepository · TaskRunner core domain catalog users moderation reports notifications GraphQL gateway single endpoint · /query Auth middleware session cookie · RBAC Error translator localized errors Observability request ID · metrics · health PostgreSQLrepositories · search Redis · in-memorycache · KV store · trends Elasticsearchoptional search engine Cloudflare R2presigned URLs · cleanup In-app · SMTPnotification channels Gemini · eBayAI and market providers Worker pooloutbox · time decay Revalidation webhookfrontend cache invalidation
Figure 3 Hexagonal architecture. Dependencies point inward: services see only ports, and modules talk to each other through small interfaces owned by the consumer.

Layers

  • Primary adapters: each module's handler.go defines its GraphQL types, queries and mutations; they validate input, check permissions and call services. No business logic.
  • Core domain: entities and validated DTOs (domain.go), use cases (service.go) and ports (repository.go).
  • Secondary adapters: PostgreSQL, Redis, R2, notification senders and external providers, wired in cmd/api.

Patterns

  • CQRS: cached reads are separated from transactional writes.
  • Worker pool: a fixed number of workers with a bounded queue; when full, tasks are dropped and logged instead of blocking users.
  • Outbox: approvals write an event in the same transaction; a poller syncs the search engine in batches and marks events processed or failed.
  • Strategy (notifications): in-app and email channels respect user preferences, while critical messages always go through.

08

AI & Market Engine

AI archivist · Gemini 3.6 Flash

During the contribution wizard, WebP images are sent as Base64 with the brand name. The AIProvider adapter asks Gemini, acting as a "fashion archivist", to return strict JSON with name, category, gender, season and designer.

The parser strips Markdown fences, ignores extra keys, normalizes unknown genders to Unisex, and on malformed output the wizard simply continues with manual entry.

Lazy market engine · eBay Browse API

When an approved item is viewed and its price history is missing or older than seven days, an estimate is queued on the worker pool. A Redis cooldown prevents concurrent and repeated calls.

The engine queries brand, name and season, takes the median of the first ten valid offers and stores it in the price history. A mock provider keeps local development independent of eBay.

09

Security & Privacy

Accounts

Two-step registration with an e-mailed one-time code, bcrypt-hashed passwords and limited verification attempts.

Sessions

A signed JWT lives only in an HttpOnly, Secure, SameSite cookie, out of reach of JavaScript; nothing is kept in localStorage.

Access control

Guest, user and admin roles enforced in resolvers, with a protected super-admin. Banned or suspended accounts are downgraded on every request.

Abuse protection

Edge and application rate limiting on login, verification and reports, keyed on the real client IP provided by Cloudflare.

Password recovery

Single-use, short-lived tokens; unknown addresses return no error to prevent user enumeration.

Privacy by design

Parameterized SQL, no e-mail addresses, clear-text IPs or tokens in logs, e-mail never searchable by admins, and GDPR deletion through anonymization.

10

Testing & Quality Assurance

Backend

  • Unit tests on services and DTO validation, with ports replaced by mocks or in-memory fakes.
  • Integration tests against real PostgreSQL and Redis in the lab environment, including migration idempotency.
  • End-to-end tests of GraphQL schemas and middleware: authentication, RBAC and context injection.
  • Concurrency: everything runs with the Go race detector.
  • Blocking build: a dedicated Docker test stage fails the image build on any failing assertion.

Frontend

  • Unit tests for the global store and shared utilities.
  • Integration tests for the network client and authentication flows.
  • Component tests for complex logic such as optimistic updates and rollbacks.