Caching (ob:cache & HTTP/Template Caching)¶
Orbita includes a three-layer caching architecture built directly in Rust with zero external dependencies:
- Compiled
.htmlTemplate Cache (automatic) — compiles each.htmltemplate into Luau once in memory, while keeping request data 100% dynamic. - HTTP Asset Caching (
ETag+304+{{ asset(...) }}) (automatic) — Symfony AssetMapper-style content-hashed URLs, conditional304 Not Modifiedresponses, and optimalCache-Controlheaders. - Application KV Cache (
ob:cache) — thread-safe in-memory key-value store with TTL, LRU eviction (max_entries), prefix invalidation, andcache.remember(...).
Layer 1: Compiled .html Template Cache¶
Every .html route template (index.html, _layout.html, components loaded via html.template(...)) is compiled from Orbita template syntax (@if, @for, {{ }}, :attr) into Luau source.
- Production / single-file binary (
ob build --compile): each.htmltemplate is compiled once and cached in memory. Subsequent requests skip disk I/O and HTML parsing completely, executing the compiled template directly with fresh per-request data. - Development (
ob run --watch): Orbita checks each template file'smtimeautomatically and recompiles immediately whenever you save an.htmlfile.
Important: Template caching caches only the compiled template logic, never user-specific rendered HTML. Dynamic routes like
/products/:idshare a single compiled template entry in memory while rendering fresh data on every request.
Layer 2: HTTP Asset Caching & {{ asset(...) }}¶
Automatic ETag, 304 Not Modified, and Cache-Control¶
When serving static files via app:static("/public", "public"), Orbita automatically:
- Computes and caches a content-based
ETag(16-character SHA-256 hex digest). - Checks the incoming
If-None-Matchheader (supporting exact, weakW/"...", multi-value, and*matches) and responds with304 Not Modified(empty body) when unchanged. - Sets
Cache-Controlautomatically: - In
--watchdev mode:no-cache(always revalidates viaETag). - In production with a versioned
?v=<hash>query string:public, max-age=31536000, immutable. - In production without
?v=:public, max-age=3600. - Handles
HEADrequests without sending the file body.
Cache-Busting with {{ asset(...) }}¶
Every .html template has access to the built-in asset(path) helper (also available in Lua as html.asset(path)):
<head>
<link rel="stylesheet" href="{{ asset('styles.css') }}" />
</head>
<body>
<slot />
<script src="{{ asset('app.js') }}"></script>
</body>
Orbita resolves styles.css against your mounted static directories (both filesystem and embedded binaries), hashes its contents, and outputs:
Whenever styles.css changes, the ?v= hash changes automatically, forcing browsers and CDNs to fetch the new version immediately while keeping immutable 1-year caching in production.
Layer 3: Application Cache (ob:cache)¶
ob:cache is a thread-safe in-memory key-value cache shared across all HTTP requests in the process. It supports strings, numbers, booleans, and nested Lua tables/arrays.
cache.remember(key, ttl_seconds, fn)¶
The recommended Laravel/Rails-style pattern for caching database queries or expensive computations (e.g. dynamic routes like /products/:id):
local cache = require("ob:cache")
local Products = require("../../models/product")
return {
load = function(ctx)
local id = ctx.params.id
local product = cache.remember("product:" .. id, 300, function()
return Products:find(id)
end)
if not product then
return ctx:not_found()
end
return { product = product }
end
}
If "product:42" is present and not expired, remember returns the cached value without calling fn. Otherwise, it calls fn(), caches any non-nil result for ttl_seconds (pass nil or 0 for no expiration), and returns it.
Invalidation¶
Invalidate a single entry when a record is updated, or an entire namespace with delete_prefix:
-- Single item invalidation
cache.delete("product:" .. id)
-- Invalidate all cached task lists for a user
local removed = cache.delete_prefix("tasks:user:" .. user_id .. ":")
-- Clear the entire application cache
cache.clear()
API Reference¶
| Function | Signature | Description |
|---|---|---|
cache.get |
(key: string) -> any \| nil |
Returns the cached value or nil if missing/expired. Updates LRU recency. |
cache.set |
(key: string, value: any, ttl_seconds?: number) -> boolean |
Stores value with optional TTL in seconds (nil/0 = no expiry). Setting nil deletes the key. |
cache.has |
(key: string) -> boolean |
Checks whether a non-expired key exists. |
cache.delete |
(key: string) -> boolean |
Removes a key. Returns true if it existed. |
cache.delete_prefix |
(prefix: string) -> number |
Removes all keys starting with prefix and returns the number of removed keys. |
cache.clear |
() -> nil |
Clears all entries from the application cache. |
cache.remember |
(key: string, ttl_seconds: number \| nil, fn: () -> any) -> any |
Returns cached value or computes, caches, and returns fn(). |
cache.configure |
({ max_entries?: number }) -> nil |
Sets the maximum number of cached entries (default 10000). When full, expired keys are purged first and then least-recently-used (LRU) entries are evicted. |
cache.stats |
() -> table |
Returns { size, max_entries, hits, misses, templates_cached, assets_cached }. |
Memory Protection (max_entries)¶
To prevent unbounded RAM growth on high-cardinality routes (such as /products/:id with thousands of items), ob:cache enforces a default limit of 10,000 entries with automatic expired-entry purging and LRU eviction. You can adjust this limit at startup: