Database Architecture
RedeCasas uses two Cloudflare storage services: D1 (SQLite) for relational data and KV for ephemeral session tokens.
D1 (SQLite)
The D1 database is defined in db/schema.sql and seeded via db/seeder/.
Schema Domains
| Domain | Tables |
|---|---|
| Geographic | brazil_regions, brazil_states, geo_region_types, geo_regions, brazil_cities |
| Content Config | scopes, topics, page_types |
| Pages | pages, page_content_cache, page_generation_log |
| Real Estate | property_types, listings, real_estate_agents, imobiliarias |
| Blog | blog_themes, blog_posts |
| Ads | city_ads |
| Analytics | notfound_urls, page_views, search_queries |
| Scheduler | daily_rotation_tracker |
Key Design Patterns
- Slugs are used for URLs:
sao-paulo,rio-de-janeiro,energia-solar - Content caching:
page_content_cachestores pre-rendered HTML so the site generator doesn’t need to re-query all relationships on every build - Analytics:
notfound_urlstracks 404s from production so the generator can create missing pages
KV (Key-Value)
KV is used exclusively for session storage.
Session Key Format
- Key:
session:{token}(random 32-byte hex string) - Value:
{ userId, email, createdAt, expiresAt } - TTL: 7 days (604800 seconds)
Why KV for Sessions?
- Sub-millisecond reads — faster than D1 for auth validation on every request
- Instant revocation — delete the key and the session is gone
- No migration needed — session schema changes don’t require ALTER TABLE
- Auto-expiry — TTL means old sessions clean themselves up
Local Development
For local development, use SQLite directly:
cd dbsqlite3 redecasas.db < schema.sqlWorkers running with wrangler dev will use the local D1 emulator if configured in wrangler.toml.