# humdinger-g/short-links architecture

> Architecture diagram of the GitHub repository humdinger-g/short-links, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-04-03). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/humdinger-g/short-links
- Repository: https://github.com/humdinger-g/short-links

## Overview

1. **System shape**
   - This repository implements a short-link platform with two separate clients:
     - a **FastAPI backend API** in `app/`
     - a lightweight **Streamlit UI** in `streamlit_app/`
   - The backend owns all business logic, persistence, authentication, caching, and background cleanup.

2. **Request entrypoints**
   - The backend starts from `app/main.py`, with app lifecycle wiring in `app/lifecycle.py`.
   - API routes are grouped under `app/api/router.py` and split into:
     - `app/api/routes/auth.py`
     - `app/api/routes/links.py`
   - The Streamlit app is a thin consumer that calls the API through `streamlit_app/api_client.py`; it does not talk directly to the database.

3. **Domain subsystems**
   - **Auth subsystem**: `app/auth/` handles registration, login, token/security concerns, and auth dependencies.
   - **Links subsystem**: `app/links/` contains the link business service, link-specific schemas, Redis cache helpers, and cleanup logic.
   - **Persistence subsystem**: `app/db/` contains SQLAlchemy models, session setup, and base metadata.
   - **Configuration subsystem**: `app/settings.py` centralizes environment-driven settings.

4. **Core data flow for authentication**
   - User registration and login are handled via the auth routes.
   - Credentials are validated, passwords are hashed, and bearer tokens are issued.
   - Protected link operations use auth dependencies to resolve the current user and enforce ownership checks.
   - User records are stored in PostgreSQL in the `users` table.

5. **Core data flow for short links**
   - `POST /links/shorten` creates link records in PostgreSQL.
   - A link may be anonymous or owned by an authenticated user.
   - The service supports `custom_alias` and `expires_at`.
   - `GET /links/{short_code}` resolves the short code, increments usage counters, updates last-used timestamps, and returns a redirect response.

6. **Link lifecycle and ownership**
   - `PUT /links/{short_code}` and `DELETE /links/{short_code}` are restricted to the owner.
   - The service layer is the boundary where ownership, alias uniqueness, expiration, and activity rules are enforced.
   - Expired links are treated as inactive even before physical cleanup occurs.

7. **Caching and invalidation**
   - Redis is used as a read-through cache for:
     - `GET /links/search`
     - `GET /links/{short_code}/stats`
   - Cache invalidation happens on link creation, redirect, update, delete, and background cleanup.
   - Cache TTL is constrained both by global settings and by the link’s own `expires_at`, so expired data cannot outlive the link.

8. **Background cleanup and archival**
   - `app/lifecycle.py` and `app/links/cleanup.py` support periodic background jobs.
   - Two cleanup policies exist:
     - automatic removal of links after `expires_at`
     - automatic removal of unused links after `UNUSED_LINK_DAYS`
   - Deleted links are archived into `archived_links`, preserving history and deletion reason (`expired` or `unused`).
   - `GET /links/history/expired` exposes that archived history.

9. **Database and migrations**
   - PostgreSQL is the primary durable store.
   - SQLAlchemy 2 is used for the ORM/persistence layer.
   - Alembic manages schema evolution, with migrations in `alembic/versions/`.
   - The README indicates Docker Compose runs `alembic upgrade head` before starting the app, so schema migration is part of startup orchestration.

10. **Deployment and runtime environment**
   - `docker-compose.yml` coordinates the backend, PostgreSQL, Redis, and Streamlit.
   - `Dockerfile` packages the backend runtime.
   - `.env.example` documents the operational configuration:
     - database and Redis URLs
     - auth secret and token TTL
     - cache TTL
     - cleanup intervals
     - public base URL used by the UI when displaying short links

11. **Testing and validation boundaries**
   - The repo is organized for both unit and functional validation:
     - `tests/unit/` covers auth, DB session/lifecycle, link service/cache/cleanup, and schemas
     - `tests/functional/` exercises the API end-to-end
     - `tests/load/` contains a Locust scenario for traffic testing
   - Coverage artifacts in `htmlcov/` and `reports/` indicate the project is already instrumented for quality tracking.

12. **Architecture summary**
   - Conceptually, the backend is a three-layer system:
     - **API layer**: FastAPI routes and request/response schemas
     - **Domain layer**: auth and link services, business rules, cleanup logic
     - **Infrastructure layer**: PostgreSQL, Redis, SQLAlchemy, Alembic, and background tasks
   - The Streamlit app is an external presentation client on top of that API, not part of the core service boundary.

Main entry points: [`app/links/service.py`](https://github.com/humdinger-g/short-links/blob/main/app/links/service.py) (Link service), [`app/api/router.py`](https://github.com/humdinger-g/short-links/blob/main/app/api/router.py) (API router), [`app/api/routes/links.py`](https://github.com/humdinger-g/short-links/blob/main/app/api/routes/links.py) (Link routes), [`app/main.py`](https://github.com/humdinger-g/short-links/blob/main/app/main.py) (App start)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_client["Client"]
  node_streamlit_app["Streamlit UI<br/>presentation app<br/>[app.py]"]
  node_api_client["API client<br/>http client<br/>[api_client.py]"]
end

subgraph group_backend_api["API"]
  node_app_main["App start<br/>fastapi entry<br/>[main.py]"]
  node_api_router["API router<br/>route assembly<br/>[router.py]"]
  node_api_auth_route["Auth routes<br/>HTTP routes<br/>[auth.py]"]
  node_api_links_route["Link routes<br/>HTTP routes<br/>[links.py]"]
end

subgraph group_domain["Domain"]
  node_auth_dependencies["Auth deps<br/>request auth<br/>[dependencies.py]"]
  node_auth_security["Security<br/>credentials/tokens<br/>[security.py]"]
  node_auth_schemas["Auth schemas<br/>dto schemas<br/>[schemas.py]"]
  node_links_service["Link service<br/>business rules<br/>[service.py]"]
  node_links_cleanup["Cleanup<br/>background maintenance<br/>[cleanup.py]"]
  node_links_schemas["Link schemas<br/>dto schemas<br/>[schemas.py]"]
end

subgraph group_infra["Infrastructure"]
  node_app_lifecycle["Lifecycle<br/>startup jobs<br/>[lifecycle.py]"]
  node_links_cache["Link cache<br/>redis cache<br/>[cache.py]"]
  node_db_session["DB session<br/>sqlalchemy session<br/>[session.py]"]
  node_db_models["Data models<br/>orm models<br/>[models.py]"]
  node_db_base["Base metadata<br/>orm base<br/>[base.py]"]
  node_settings["Settings<br/>env config<br/>[settings.py]"]
end

subgraph group_delivery["Delivery"]
  node_alembic_env["Alembic env<br/>migration runtime<br/>[env.py]"]
  node_initial_migration["Schema mig<br/>migration set"]
  node_functional_api["API tests<br/>functional tests<br/>[test_links_api.py]"]
end

node_app_main -->|"mounts"| node_api_router
node_app_main -->|"starts"| node_app_lifecycle
node_app_main -->|"reads"| node_settings
node_api_router -->|"includes"| node_api_auth_route
node_api_router -->|"includes"| node_api_links_route
node_api_auth_route -->|"uses"| node_auth_security
node_api_auth_route -->|"validates"| node_auth_schemas
node_api_links_route -->|"calls"| node_links_service
node_api_links_route -->|"protects"| node_auth_dependencies
node_api_links_route -->|"validates"| node_links_schemas
node_auth_dependencies -->|"verifies"| node_auth_security
node_links_service -->|"persists"| node_db_session
node_links_service -->|"maps"| node_db_models
node_links_service -->|"invalidates"| node_links_cache
node_links_service -->|"uses"| node_settings
node_links_service -->|"enforces"| node_auth_dependencies
node_links_cache -->|"reads through"| node_db_session
node_links_cleanup -->|"archives"| node_db_session
node_links_cleanup -->|"purges"| node_links_cache
node_app_lifecycle -->|"schedules"| node_links_cleanup
node_db_models -->|"extends"| node_db_base
node_alembic_env -->|"imports"| node_db_base
node_alembic_env -->|"runs"| node_initial_migration
node_streamlit_app -->|"uses"| node_api_client
node_api_client -->|"calls"| node_api_router
node_functional_api -.->|"exercises"| node_api_router

click node_app_main "https://github.com/humdinger-g/short-links/blob/main/app/main.py"
click node_app_lifecycle "https://github.com/humdinger-g/short-links/blob/main/app/lifecycle.py"
click node_api_router "https://github.com/humdinger-g/short-links/blob/main/app/api/router.py"
click node_api_auth_route "https://github.com/humdinger-g/short-links/blob/main/app/api/routes/auth.py"
click node_api_links_route "https://github.com/humdinger-g/short-links/blob/main/app/api/routes/links.py"
click node_auth_dependencies "https://github.com/humdinger-g/short-links/blob/main/app/auth/dependencies.py"
click node_auth_security "https://github.com/humdinger-g/short-links/blob/main/app/auth/security.py"
click node_auth_schemas "https://github.com/humdinger-g/short-links/blob/main/app/auth/schemas.py"
click node_links_service "https://github.com/humdinger-g/short-links/blob/main/app/links/service.py"
click node_links_cache "https://github.com/humdinger-g/short-links/blob/main/app/links/cache.py"
click node_links_cleanup "https://github.com/humdinger-g/short-links/blob/main/app/links/cleanup.py"
click node_links_schemas "https://github.com/humdinger-g/short-links/blob/main/app/links/schemas.py"
click node_db_session "https://github.com/humdinger-g/short-links/blob/main/app/db/session.py"
click node_db_models "https://github.com/humdinger-g/short-links/blob/main/app/db/models.py"
click node_db_base "https://github.com/humdinger-g/short-links/blob/main/app/db/base.py"
click node_settings "https://github.com/humdinger-g/short-links/blob/main/app/settings.py"
click node_streamlit_app "https://github.com/humdinger-g/short-links/blob/main/streamlit_app/app.py"
click node_api_client "https://github.com/humdinger-g/short-links/blob/main/streamlit_app/api_client.py"
click node_alembic_env "https://github.com/humdinger-g/short-links/blob/main/alembic/env.py"
click node_initial_migration "https://github.com/humdinger-g/short-links/tree/main/alembic/versions"
click node_functional_api "https://github.com/humdinger-g/short-links/blob/main/tests/functional/test_links_api.py"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_streamlit_app,node_api_client toneBlue
class node_app_main,node_api_router,node_api_auth_route,node_api_links_route toneAmber
class node_auth_dependencies,node_auth_security,node_auth_schemas,node_links_service,node_links_cleanup,node_links_schemas toneMint
class node_app_lifecycle,node_links_cache,node_db_session,node_db_models,node_db_base,node_settings toneRose
class node_alembic_env,node_initial_migration,node_functional_api toneIndigo
```

## Components

### Client

Thin Streamlit presentation layer

- [Streamlit UI](https://github.com/humdinger-g/short-links/blob/main/streamlit_app/app.py): presentation app · Lightweight user-facing client · `streamlit_app/app.py`
- [API client](https://github.com/humdinger-g/short-links/blob/main/streamlit_app/api_client.py): http client · Streamlit-side API consumer · `streamlit_app/api_client.py`

### API

FastAPI entrypoints and request routing

- [App start](https://github.com/humdinger-g/short-links/blob/main/app/main.py): fastapi entry · Backend application entrypoint · `app/main.py`
- [API router](https://github.com/humdinger-g/short-links/blob/main/app/api/router.py): route assembly · Top-level API router composition · `app/api/router.py`
- [Auth routes](https://github.com/humdinger-g/short-links/blob/main/app/api/routes/auth.py): HTTP routes · Registration and login endpoints · `app/api/routes/auth.py`
- [Link routes](https://github.com/humdinger-g/short-links/blob/main/app/api/routes/links.py): HTTP routes · Short-link CRUD, redirect, search, and history endpoints · `app/api/routes/links.py`

### Domain

Auth and link business logic

- [Auth deps](https://github.com/humdinger-g/short-links/blob/main/app/auth/dependencies.py): request auth · Current-user resolution and ownership enforcement · `app/auth/dependencies.py`
- [Security](https://github.com/humdinger-g/short-links/blob/main/app/auth/security.py): credentials/tokens · Password hashing and bearer token handling · `app/auth/security.py`
- [Auth schemas](https://github.com/humdinger-g/short-links/blob/main/app/auth/schemas.py): dto schemas · Authentication request and response models · `app/auth/schemas.py`
- [Link service](https://github.com/humdinger-g/short-links/blob/main/app/links/service.py): business rules · Link creation, lookup, update, ownership, and expiry rules · `app/links/service.py`
- [Cleanup](https://github.com/humdinger-g/short-links/blob/main/app/links/cleanup.py): background maintenance · Expiration and unused-link archival jobs · `app/links/cleanup.py`
- [Link schemas](https://github.com/humdinger-g/short-links/blob/main/app/links/schemas.py): dto schemas · Link request, response, and history models · `app/links/schemas.py`

### Infrastructure

Persistence, cache, settings, and runtime wiring

- [Lifecycle](https://github.com/humdinger-g/short-links/blob/main/app/lifecycle.py): startup jobs · App startup and background task wiring · `app/lifecycle.py`
- [Link cache](https://github.com/humdinger-g/short-links/blob/main/app/links/cache.py): redis cache · Read-through caching and invalidation for search and stats · `app/links/cache.py`
- [DB session](https://github.com/humdinger-g/short-links/blob/main/app/db/session.py): sqlalchemy session · Database engine and session management · `app/db/session.py`
- [Data models](https://github.com/humdinger-g/short-links/blob/main/app/db/models.py): orm models · SQLAlchemy models and metadata for users and links · `app/db/models.py`
- [Base metadata](https://github.com/humdinger-g/short-links/blob/main/app/db/base.py): orm base · Declarative base and shared metadata · `app/db/base.py`
- [Settings](https://github.com/humdinger-g/short-links/blob/main/app/settings.py): env config · Environment-driven application configuration · `app/settings.py`

### Delivery

Migrations and validation

- [Alembic env](https://github.com/humdinger-g/short-links/blob/main/alembic/env.py): migration runtime · Migration environment and schema orchestration · `alembic/env.py`
- [Schema mig](https://github.com/humdinger-g/short-links/tree/main/alembic/versions): migration set · Versioned schema evolution scripts · `alembic/versions`
- [API tests](https://github.com/humdinger-g/short-links/blob/main/tests/functional/test_links_api.py): functional tests · End-to-end API validation coverage · `tests/functional/test_links_api.py`

## Connections

- App start → API router: mounts · Registers API routes
- App start → Lifecycle: starts · Initializes startup/shutdown hooks
- App start → Settings: reads · Loads runtime configuration
- API router → Auth routes: includes · Adds auth endpoints
- API router → Link routes: includes · Adds link endpoints
- Auth routes → Security: uses · Hashes passwords and issues tokens
- Auth routes → Auth schemas: validates · Shapes auth requests and responses
- Link routes → Link service: calls · Delegates link operations to the service layer
- Link routes → Auth deps: protects · Resolves authenticated users for protected actions
- Link routes → Link schemas: validates · Shapes link and history payloads
- Auth deps → Security: verifies · Checks bearer tokens and identity
- Link service → DB session: persists · Reads and writes link and user records
- Link service → Data models: maps · Operates on ORM entities
- Link service → Link cache: invalidates · Maintains cache coherence
- Link service → Settings: uses · Applies cache and cleanup configuration
- Link service → Auth deps: enforces · Checks ownership for updates and deletes
- Link cache → DB session: reads through · Cache misses fall back to persistence
- Cleanup → DB session: archives · Moves expired and unused links to history
- Cleanup → Link cache: purges · Invalidates stale cached entries
- Lifecycle → Cleanup: schedules · Runs periodic maintenance jobs
- Data models → Base metadata: extends · Builds the declarative model layer
- Alembic env → Base metadata: imports · Binds migration metadata
- Alembic env → Schema mig: runs · Applies versioned schema changes
- Streamlit UI → API client: uses · Delegates all backend calls to the client
- API client → API router: calls · Consumes the backend API
- API tests → API router: exercises · Validates end-to-end API behavior
