Request Lifecycle
Understanding imgforge’s internal workflow helps you reason about performance, error handling, and observability. Each request flows through the following stages:
Request flow diagram
┌─────────────────────────────────────────────────────────────────────────────┐
│ Request Lifecycle │
└─────────────────────────────────────────────────────────────────────────────┘
┌──────────────────────┐
│ Incoming Request │ → HTTP GET /<sig>/<options>/<source>
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Routing & Middleware │ → Attach tracing spans
│ │ Rate limiting check (429 if depleted)
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ URL Parsing & │ → Split: signature | options | source
│ Authentication │ HMAC validation (403 if invalid)
│ │ Bearer token check (401 if required)
└──────────┬───────────┘
│
▼
┌──────────────────────┐ ┌─────────────┐
│ Cache Lookup │────────▶│ Cache Hit? │─┐
│ (Memory/Disk/Hybrid) │ └─────────────┘ │
└──────────────────────┘ │
│ │ YES
│ NO │
▼ │
┌──────────────────────┐ │
│ Source Acquisition │ → Acquire semaphore │
│ │ Download image │
│ │ Validate size/MIME │
│ │ Check resolution │
│ │ Fetch watermark │
└──────────┬───────────┘ │
│ │
▼ │
┌──────────────────────┐ │
│ Option Parsing │ → Parse directives │
│ │ Validate ranges │
└──────────┬───────────┘ │
│ │
▼ │
┌──────────────────────┐ │
│ Image Transformation │ → libvips pipeline │
│ (see Pipeline doc) │ 7-stage process │
└──────────┬───────────┘ │
│ │
▼ │
┌──────────────────────┐ │
│ Cache Populate │ → Store in cache │
│ (on success) │ │
└──────────┬───────────┘ │
│ │
├─────────────────────────────────────┘
▼
┌──────────────────────┐
│ Response Composition │ → 200 OK + Content-Type
│ │ X-Request-ID header
│ │ Processed image bytes
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Metrics & Logging │ → Record durations & counters
│ │ Update Prometheus metrics
└──────────┬───────────┘
│
▼
┌──────────────────────┐
│ Client Receives │ → Image delivered
└──────────────────────┘
Error Paths:
• 403 Forbidden ←───────────── Signature/auth failure
• 400 Bad Request ←─────────── Invalid options, oversized, bad MIME
• 429 Too Many Requests ←───── Rate limit exceeded
• 504 Gateway Timeout ←─────── Processing timeout
• 500 Internal Error ←──────── Unhandled exceptions1. Routing & middleware
- Ingress – The Axum router accepts the HTTP request and attaches structured tracing spans so every hop can be correlated in logs.
- Rate limiting – When
IMGFORGE_RATE_LIMIT_PER_MINUTEis set, a global token bucket checks capacity before the request proceeds, responding with429 Too Many Requestswhen depleted. - Response classification – Status-code counters increment as responses leave the service, powering dashboards and alerts.
2. URL parsing & authentication
- Path parsing – imgforge splits the path into signature, processing directives, and the source segment. Invalid layouts fail fast with
400 Bad Request. - Signature validation – Unless the signature literal is
unsafe, the server recomputes the HMAC usingIMGFORGE_KEYandIMGFORGE_SALT. Mismatches return403 Forbidden. See the “Signing a URL” section in URL Structure. - Bearer token – When
IMGFORGE_SECRETis configured, image and info endpoints requireAuthorization: Bearer <token>and return401 Unauthorizedotherwise.
3. Cache lookup
With caching enabled, imgforge hashes the full request path and checks the configured backend:
- Memory cache – Constant-time lookups backed by Foyer’s in-memory store.
- Disk / hybrid cache – Asynchronous lookups using Foyer’s block engine and optional persistent storage.
- Cache hits short-circuit the lifecycle, returning cached bytes immediately. Metrics such as
cache_hits_totalandcache_misses_totalcapture effectiveness.
4. Source acquisition
- Permit acquisition – Unless the
rawoption is set, the request acquires a semaphore permit (up toIMGFORGE_WORKERSconcurrent jobs) to contain libvips concurrency. - Download – The source image is fetched with
reqwestwithinIMGFORGE_DOWNLOAD_TIMEOUTseconds. - Validation – imgforge enforces:
- File size limits from
IMGFORGE_MAX_SRC_FILE_SIZEor a per-request override. - MIME type allowlists via
IMGFORGE_ALLOWED_MIME_TYPES. - Resolution ceilings using EXIF dimensions and
IMGFORGE_MAX_SRC_RESOLUTION.
- File size limits from
- Watermark assets – When the URL specifies
watermark_urlor the server setsIMGFORGE_WATERMARK_PATH, the watermark image is fetched or read from disk alongside the source.
Failures at this stage return 400 Bad Request with descriptive messages (see Error Troubleshooting).
5. Option parsing
The processing directives are parsed into a structured plan. Out-of-range values, invalid booleans, or malformed numbers produce 400 Bad Request responses. The full directive catalogue lives in Processing Options.
6. Image transformation
With a validated plan, imgforge executes the transformation chain:
- Device-pixel-ratio scaling adjusts requested dimensions and padding.
- libvips loads the source buffer into memory and applies EXIF orientation correction.
- Transformations—crops, resizes, extension, padding, rotations, effects, watermarking, and background flattening—execute in a deterministic order.
- The processed image is encoded into the requested format and quality.
For a deeper dive into the sequencing, defaults, and error surfaces inside this phase, see Image Processing Pipeline.
Processing duration is recorded in the image_processing_duration_seconds histogram and increments processed_images_total.
7. Response & caching
- Cache populate – On success, the rendered bytes are inserted into the configured cache. Failures to write are logged but do not affect the response.
- Response composition – imgforge returns
200 OKwith the processed bytes and appropriateContent-Type. Additional headers includeX-Request-IDfor log correlation plus any validation headers inherited from earlier stages.
8. Metrics & logging
- Fetch durations feed
source_image_fetch_duration_secondsand thesource_images_fetched_totalcounter (labeled by outcome). - Request spans include method, URI, and a random request ID, making it easy to correlate logs, traces, and metrics.
/metricsaggregates all counters and histograms for scraping. Dashboards and alerting playbooks are documented in Prometheus Monitoring.
Error pathways
- Signature / auth – Returns
403 Forbiddenor401 Unauthorizeddepending on the failure. - Invalid options – Returns
400 Bad Requestwith a plain-text reason string. - Timeouts –
504 Gateway Timeoutfor processing timeouts,408 Request Timeoutif an upstream proxy times out first, or400 Bad Requestwhen the download timeout triggers. - Unhandled errors – Logged at
errorlevel and surfaced as500 Internal Server Error.
Understanding each stage helps you tune performance, design observability dashboards, and debug issues quickly.