About the Technology
Technical overview of the architecture and tools behind DanceStats.eu
Python
3.15
Flask
3.1
PostgreSQL
18
Gunicorn
26
Vite
8
PyTorch
2.x
Core Stack
| Layer | Technology | Detail |
|---|---|---|
| Language | Python 3.15 | Main backend language |
| Framework | Flask 3.1 | Micro-framework with blueprints and templating system |
| WSGI | Gunicorn 26 | Multi-worker WSGI server for production |
| Database | PostgreSQL 18 | Connection pooling, TCP keepalive, slow query tracking |
| Templating | Jinja2 | Templates with inheritance, macros and blocks |
| Frontend | JavaScript + Alpine.js | ES modules with Alpine.js reactivity and htmx server interactions |
| Reactivity | Alpine.js | CSP-safe build - reactive UI without unsafe-eval |
| Server interactions | htmx | Declarative AJAX with CSRF token injection |
| Charts | Chart.js + CspChart | Custom SVG chart library for strict-CSP pages - Chart.js on the data-heavy ones |
| Bundler | Vite 8 | ES module bundling with content-hash filenames and tree-shaking |
Machine Learning & Predictions
DanceTransformer - Neural Network
- PyTorch Transformer with multi-head attention
- Embeddings for couples, adjudicators, clubs, dancers and federations - new couples handled by composing both dancers' embeddings (cold-start)
- 42 per-couple numerical features + 5 adjudicator-couple interaction features (cross-attention over the panel) + categorical embeddings for discipline, age and class
- CPU-only inference in production
- Incremental fine-tuning on new data without retraining from scratch
Elo Engine (Model B) - Statistical Model
- Dynamic K-factor based on couple experience
- 8 adjustment factors: momentum, adjudicator-club compatibility, promotion uncertainty, age effect, inactivity, transitive adjustments, partnership quality, head-to-head
- Rating inheritance from previous partnerships
- Adjudicator–club compatibility matrix recomputed from historical results
- Ratings for every federation with enough results: one per federation and one combined cross-federation rating used by every leaderboard, updated within about half an hour of new results
- Each result counts the round a couple reached and every adjudicator's marks in every round; moving up a class widens the rating's uncertainty instead of subtracting points
Ensemble - combined output
- Confidence-weighted average of three models, the neural network, the Elo model and the couples' head-to-head record, with automatic weight tuning
- Per-couple agreement metric (0–1) - higher values indicate more reliable predictions
Architecture & Code Organisation
| Component | Description |
|---|---|
| Flask Blueprints | Domain-specific modules for code organisation |
| Jinja2 templates | Templates with inheritance and reusable macros |
| Utility modules | Configuration, cache, translations, database helpers |
85 blueprints
1,408 templates
795 JS files
1,162 utility modules
213 services
Public REST API
- Versioned API (/api/v1, /api/v2) exposing competitions, events, dancers, adjudicators and rankings across every federation
- Auto-generated OpenAPI 3.1 spec with live Swagger UI at /api/v1/docs; API v2 publishes its own spec at /api/v2/openapi.json
- Bearer-token authentication with per-token scopes and request rate limiting
- Conditional ETag / If-None-Match requests with 304 responses and cache headers
- Pydantic v2 schemas drive request validation and response serialisation
- Publishable keys for third-party sites (SHA-256 digest, domain allowlist, revocable) serving iframe widgets and JSON for club and personal showcases
OpenAPI 3.1
Swagger UI
Pydantic v2
Bearer tokens
ETag / 304
Internationalisation (i18n)
- UI languages: 25 (cs, en, uk, sk, de, nl, hu, es, pt, pl, it, fr, tr, ro, el, sv, da, no, fi, hr, lt, lv, sr, sl, et) - full support with CI-enforced translation parity; automatic detection via Cloudflare CF-IPCountry
- Translation keys per language across the locale families (28113)
- Translation functions for UI strings, data values and plural forms (CLDR)
- Plural forms per language via CLDR (Babel); Czech: singular (1), few (2-4), many (0, 5+)
- Translations for age categories, disciplines, dances, rounds, competition types, countries
- Language addresses such as /cs/, /sk/ and /en/ for the main pages, each listed separately by search engines
Asset Pipeline & Performance
CSS
- Modular CSS: base/, components/ (64), layouts/, pages/, themes/
- main.css as entry point - @imports inlined into a single main.bundled.css, served minified; the dark theme and a few page-only stylesheets are separate files
- Dark mode as its own stylesheet, downloaded only when the dark theme is switched on
JavaScript
- JavaScript source files (core + page-specific + admin + booking) - 795
- Production minification via Vite (Rolldown) with tree-shaking
- Vite bundler with ES modules, content-hash filenames, and vendor chunking
Caching
4-tier cache architecture with automatic promotion and fail-open fallback:
| Tier | Technology | Detail |
|---|---|---|
| L0 | lru_cache | Ultra-hot reference data (64 entries, LRU eviction) - country codes, filter lists |
| L1 | In-memory dict | Per-worker dict with TTL - zero-latency reads, promotes from L2 on miss |
| L2 | Redis | Shared across Gunicorn workers, survives deploys - JSON serialisation with SETEX |
| L3 | PostgreSQL | HTTP response archive - zstd-compressed, retention per page type (lifetime/long/medium/short); a stored page is never replaced by an error page |
| Browser | sessionStorage | sessionStorage-backed cache for planner state (15 min TTL) |
- Read path: L0 → L1 → L2 → compute → write back to L1 + L2 (L2 only for profile data)
- Write-through: set() writes to both L1 and L2, except dancer, club and adjudicator profile data, which stays in L2 only so one-off crawler visits do not fill every worker's memory
- Fail-open design - Redis unavailability silently falls back to L1; app stays up
- Content-hash versioning for cache invalidation
Progressive Web App (PWA)
- Service worker with pre-cache for essential assets (offline page, CSS, fonts, icons)
- Static assets: cache-first strategy with ?v= cache busting
- API endpoints: stale-while-revalidate (instant cached response, background update)
- HTML pages: network-first with fallback to cache and offline page
- Offline page: pre-cached /offline page as last resort
Security
- Content Security Policy - nonce-based policy for XSS protection
- HSTS - enforced HTTPS with long-term validity
- Password-free sign-in with Google
- CSRF protection on all forms
- Role-based access control - different access levels by user type
- Rate limiting on sensitive endpoints
- Secure session cookies (HttpOnly, SameSite, Secure)
- Permissions-Policy - comprehensive restriction of browser APIs (camera, microphone, geolocation, USB, Bluetooth, and 20+ others)
- Privacy-first social sharing - the share buttons are plain links plus the native Web Share API, with no Facebook or X tracking SDKs; nothing is sent to any third party until you click, and preview cards are rendered on our own servers.
- Scripts, styles and web fonts are served from our own servers. External services are limited to map tiles and the Cloudflare Turnstile security check on the feedback form.
Cloudflare Integration
- CDN distribution of static assets (CSS, JS, fonts, images) worldwide
- Smart cache invalidation via content-hash versioning
- Edge cache for public pages - a Cloudflare Worker serves shareable pages to anonymous visitors from the nearest data centre, keyed by page, language and release, with a fresh security nonce on every hit; signed-in pages always come from our servers
- DDoS protection and DNS proxy on the free tier
Database & Migrations
- PostgreSQL - robust relational database
- Two PostgreSQL databases: one for results and statistics, one for accounts, payments and booking, each backed up separately
- Connection pooling with TCP keepalive for stable connections
- Slow query tracking with configurable threshold
- Versioned SQL migrations, each registered to the database it changes and applied in order
- Change-aware imports: re-importing a competition whose data did not change no longer marks it as changed, so the overnight processing that follows changes skips it
- Results keep their identifiers when a competition is re-imported, so a link to a single result keeps working
- Multi-federation support: ČSTS, SZTŠ, WDSF, SUT, DSI, WDC-AL, DTV, NADB, NDO, NVAD and more across Europe and beyond (70 in total)
EXCLUDE constraints
BRIN indexes
GIN / JSONB
uuidv7()
casefold()
RETURNING OLD/NEW
Virtual generated columns
Deployment & Infrastructure
- PaaS hosting with Gunicorn WSGI server
- Seven services built from one code base: the results site, sign-in, booking, a webhook receiver, two background workers and data synchronisation between the databases
- Docker image for the production deployment
- Python 3.15 with lazy loading of heavy libraries: a web process starts in about half the time and uses about a fifth less memory
- Multi-worker WSGI server with a thread pool per worker
- A synthetic check opens public pages through the public address every five minutes and alerts when they slow down
- Account, payment and booking data are backed up every hour and the other irreplaceable tables every day
Railway PaaS
HTTP/2
Auto-deploy
Cloudflare CDN
Booking Module
- Multi-tenant SaaS architecture - each club isolated at middleware and SQL level
- 250+ database tables prefixed booking_* with full tenant isolation
- Service modules (545) - payments, notifications, backups, pricing, planner
- Credit system with SELECT...FOR UPDATE locking and immutable audit log
- ClubZone/EOS connector - member import and sync from the club's own membership system
- PWA with offline support, iCal feeds, rotating per-device sign-in tokens and custom club branding
Multi-tenant
SELECT...FOR UPDATE
EXCLUDE constraints
SCD Type 2
Fernet encryption
iCal feeds
Data sources
- Place names and postal codes: GeoNames (geonames.org), licensed under CC BY 4.0.
- Japanese name readings use the JMnedict dictionary file, the property of the Electronic Dictionary Research and Development Group, used in conformance with the Group's licence.