DuckDB analytics with the official crate
This recipe uses the official duckdb
crate in a Rullst application for in-process analytics: one connection opened
at start-up, every query run off the async runtime with a row cap and a time
limit, a small application trait that handlers depend on, an in-memory fake
for handler tests, and tests against a real in-memory DuckDB. It replaces the
DuckDbStore adapter that 13.0.0-alpha.5 removed; see
Migrating from DuckDbStore. The code is yours
(see what a recipe is).
The blocks that use Rullst types (configuration, the trait, the fake, the
handler and its test) are compiled and run as doctests in Rullst’s CI. The
blocks marked as engine code are not compiled there, because the Rullst
workspace deliberately does not depend on duckdb (its bundled C++ build is
the reason the adapter was removed); they are written against the duckdb
1.x API (checked against 1.20000.1).
When to use it
DuckDB is an embedded analytical database: it answers aggregate queries over millions of rows in a local file, and reads Parquet and CSV files directly. Use it for reports and dashboards computed in one process, for example from events the application exports from its primary database. It is not a shared application database: only one process can open a database file for writing, so several replicas cannot write to the same file. Keep transactional data in the SQLx ORM.
Dependency
[dependencies]
duckdb = { version = "~1.20000.1", features = ["bundled"] }
The crate’s version encodes the DuckDB release (1.20000.x bundles DuckDB
2.0.0); the ~ requirement accepts the crate’s patch releases without moving
to another DuckDB release. bundled compiles DuckDB’s C++ engine from source:
expect a long first build and several GiB in target/. Without bundled, the
crate links a DuckDB library installed on the system (DUCKDB_LIB_DIR and
DUCKDB_INCLUDE_DIR point to it), which builds quickly but must be present
wherever the application builds and runs. The parquet and json features
add those readers.
To keep the engine out of builds that do not need it (fast CI jobs, a development machine with little disk), make the dependency optional behind a feature of your own and serve the in-memory fake when it is off:
[dependencies]
duckdb = { version = "~1.20000.1", features = ["bundled"], optional = true }
[features]
analytics = ["dep:duckdb"]
Configuration
Read the database path with rullst::config::project_setting (the process
environment first, then the project’s .env). An empty or absent
DUCKDB_PATH, or one starting with mock_, selects the in-memory fake:
#![allow(unused)]
fn main() {
use std::path::PathBuf;
use rullst::config::{ConfigError, project_setting};
/// `DUCKDB_PATH`, or `None` for the in-memory fake.
pub fn analytics_path() -> Result<Option<PathBuf>, ConfigError> {
let path = project_setting("DUCKDB_PATH")?.unwrap_or_default();
if path.is_empty() || path.starts_with("mock_") {
return Ok(None);
}
Ok(Some(PathBuf::from(path)))
}
}
# .env
DUCKDB_PATH=analytics.duckdb
Projects generated by cargo rullst new already list *.duckdb and
*.duckdb.wal in .gitignore and .dockerignore, so a local database file
reaches neither Git nor the container build context. In a container, put the
file on a volume (/app/data/analytics.duckdb in the generated image).
The application boundary
Handlers depend on a small trait that returns Send futures, and are generic
over it (static dispatch). The fake computes the same report in memory:
use std::collections::BTreeMap;
use std::fmt;
use std::future::Future;
use std::sync::{Arc, Mutex};
use rullst::Router;
use rullst::server::{Extension, IntoResponse, Json, Response, StatusCode, get};
use serde::{Deserialize, Serialize};
/// One page view, as the application records it.
#[derive(Debug, Clone)]
pub struct PageView {
pub tenant_id: String,
pub path: String,
pub duration_ms: i64,
}
/// One row of the "top pages" report.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PageStat {
pub path: String,
pub views: i64,
pub average_ms: f64,
}
/// Failures of the analytics store. Engine details stay in the server log.
#[derive(Debug)]
pub enum AnalyticsError {
/// The query did not finish within its time budget.
TimedOut,
/// The engine failed or its worker stopped.
Unavailable(String),
}
impl fmt::Display for AnalyticsError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::TimedOut => formatter.write_str("the analytics query timed out"),
Self::Unavailable(detail) => write!(formatter, "analytics unavailable: {detail}"),
}
}
}
impl std::error::Error for AnalyticsError {}
impl IntoResponse for AnalyticsError {
fn into_response(self) -> Response {
tracing::error!(error = %self, "analytics request failed");
StatusCode::SERVICE_UNAVAILABLE.into_response()
}
}
/// What the application needs from its analytics store.
pub trait PageAnalytics: Clone + Send + Sync + 'static {
/// Records one page view.
fn record(&self, view: PageView) -> impl Future<Output = Result<(), AnalyticsError>> + Send;
/// The tenant's most viewed pages, most viewed first, at most `limit`.
fn top_pages(
&self,
tenant_id: &str,
limit: u32,
) -> impl Future<Output = Result<Vec<PageStat>, AnalyticsError>> + Send;
}
fn poisoned() -> AnalyticsError {
AnalyticsError::Unavailable("the analytics lock is poisoned".to_owned())
}
/// In-process fake for handler tests and for builds without DuckDB.
#[derive(Clone, Default)]
pub struct MemoryAnalytics {
views: Arc<Mutex<Vec<PageView>>>,
}
impl PageAnalytics for MemoryAnalytics {
async fn record(&self, view: PageView) -> Result<(), AnalyticsError> {
self.views.lock().map_err(|_| poisoned())?.push(view);
Ok(())
}
async fn top_pages(
&self,
tenant_id: &str,
limit: u32,
) -> Result<Vec<PageStat>, AnalyticsError> {
let views = self.views.lock().map_err(|_| poisoned())?;
let mut totals: BTreeMap<&str, (i64, i64)> = BTreeMap::new();
for view in views.iter().filter(|view| view.tenant_id == tenant_id) {
let (count, total) = totals.entry(view.path.as_str()).or_default();
*count += 1;
*total = total.saturating_add(view.duration_ms);
}
let mut stats: Vec<PageStat> = totals
.into_iter()
.map(|(path, (count, total))| PageStat {
path: path.to_owned(),
views: count,
average_ms: total as f64 / count as f64,
})
.collect();
// The SQL report's order: most viewed first, then by path.
stats.sort_by(|left, right| {
right.views.cmp(&left.views).then_with(|| left.path.cmp(&right.path))
});
stats.truncate(limit as usize);
Ok(stats)
}
}
/// The signed-in user's tenant, inserted by the application's
/// authentication layer.
#[derive(Clone)]
pub struct CurrentTenant {
pub id: String,
}
/// Rows in the report, whatever the client asks for.
const REPORT_ROWS: u32 = 20;
/// `GET /reports/top-pages`: the signed-in tenant's report.
async fn top_pages<A: PageAnalytics>(
Extension(analytics): Extension<A>,
Extension(tenant): Extension<CurrentTenant>,
) -> Result<Json<Vec<PageStat>>, AnalyticsError> {
let report = analytics.top_pages(&tenant.id, REPORT_ROWS).await?;
Ok(Json(report))
}
/// The report routes with the store selected at start-up.
pub fn analytics_routes<A: PageAnalytics>(analytics: A) -> Router {
Router::new()
.route("/reports/top-pages", get(top_pages::<A>))
.layer(Extension(analytics))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// A unit test of the application: the fake, the real routes, no engine.
let analytics = MemoryAnalytics::default();
for (tenant_id, path, duration_ms) in [
("acme", "/pricing", 100),
("acme", "/pricing", 200),
("acme", "/docs", 50),
("globex", "/pricing", 999),
] {
let view = PageView {
tenant_id: tenant_id.into(),
path: path.into(),
duration_ms,
};
analytics.record(view).await?;
}
let app = rullst::testing::TestApp::new(
analytics_routes(analytics)
.layer(Extension(CurrentTenant { id: "acme".into() }))
.into_axum(),
);
let response = app.get("/reports/top-pages").send().await;
response.assert_status(200);
let report: Vec<PageStat> = response.json();
assert_eq!(report.len(), 2); // globex's view is not counted
assert_eq!(
report[0],
PageStat { path: "/pricing".into(), views: 2, average_ms: 150.0 }
);
Ok(())
}
Mount analytics_routes behind the authentication layer that inserts
CurrentTenant and the production security layers, like any other route.
The tenant comes from the session, never from a query parameter.
The DuckDB implementation
Engine code (not compiled by Rullst’s CI). A DuckDB Connection is Send but
not Sync, and every call blocks the calling thread. So the store opens one
connection at start-up, keeps it behind a std::sync::Mutex, and runs every
query on Tokio’s blocking pool with spawn_blocking, never on an async worker
thread:
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use duckdb::{Config, Connection, InterruptHandle, params};
use rullst::runtime::{task, time};
/// The report never materializes more rows than this.
const MAX_REPORT_ROWS: usize = 1_000;
/// How long one query may take before it is interrupted.
const QUERY_BUDGET: Duration = Duration::from_secs(5);
const SCHEMA: &str = "CREATE TABLE IF NOT EXISTS page_views (
tenant_id VARCHAR NOT NULL,
path VARCHAR NOT NULL,
duration_ms BIGINT NOT NULL
)";
/// DuckDB-backed analytics. Clones share the one connection.
#[derive(Clone)]
pub struct DuckDbAnalytics {
connection: Arc<Mutex<Connection>>,
interrupt: Arc<InterruptHandle>,
}
fn engine(error: duckdb::Error) -> AnalyticsError {
AnalyticsError::Unavailable(error.to_string())
}
fn worker_stopped() -> AnalyticsError {
AnalyticsError::Unavailable("the analytics worker stopped".to_owned())
}
impl DuckDbAnalytics {
/// Opens (or creates) the database file once, at start-up, with bounded
/// memory and threads.
pub async fn open(path: impl Into<PathBuf>) -> Result<Self, AnalyticsError> {
let path = path.into();
Self::start(move || {
let config = Config::default().max_memory("512MB")?.threads(2)?;
Connection::open_with_flags(path, config)
})
.await
}
/// An empty in-memory database, for tests.
pub async fn in_memory() -> Result<Self, AnalyticsError> {
Self::start(Connection::open_in_memory).await
}
async fn start<F>(open: F) -> Result<Self, AnalyticsError>
where
F: FnOnce() -> duckdb::Result<Connection> + Send + 'static,
{
let connection = task::spawn_blocking(move || {
let connection = open()?;
connection.execute_batch(SCHEMA)?;
Ok::<_, duckdb::Error>(connection)
})
.await
.map_err(|_| worker_stopped())?
.map_err(engine)?;
let interrupt = connection.interrupt_handle();
Ok(Self { connection: Arc::new(Mutex::new(connection)), interrupt })
}
/// Runs `work` with the connection on the blocking pool and interrupts
/// the query when it outlives `QUERY_BUDGET`.
async fn run<T, F>(&self, work: F) -> Result<T, AnalyticsError>
where
T: Send + 'static,
F: FnOnce(&Connection) -> duckdb::Result<T> + Send + 'static,
{
let connection = Arc::clone(&self.connection);
let job = task::spawn_blocking(move || {
let connection = connection.lock().map_err(|_| poisoned())?;
work(&connection).map_err(engine)
});
match time::timeout(QUERY_BUDGET, job).await {
Ok(joined) => joined.map_err(|_| worker_stopped())?,
Err(_elapsed) => {
// A blocking task cannot be cancelled: stop the query itself.
self.interrupt.interrupt();
Err(AnalyticsError::TimedOut)
}
}
}
}
impl PageAnalytics for DuckDbAnalytics {
async fn record(&self, view: PageView) -> Result<(), AnalyticsError> {
self.run(move |connection| {
connection.execute(
"INSERT INTO page_views (tenant_id, path, duration_ms) VALUES (?, ?, ?)",
params![view.tenant_id, view.path, view.duration_ms],
)
})
.await
.map(|_| ())
}
async fn top_pages(
&self,
tenant_id: &str,
limit: u32,
) -> Result<Vec<PageStat>, AnalyticsError> {
let tenant_id = tenant_id.to_owned();
let limit = (limit as usize).min(MAX_REPORT_ROWS);
self.run(move |connection| {
let mut statement = connection.prepare(
"SELECT path, count(*) AS views, avg(duration_ms) AS average_ms
FROM page_views
WHERE tenant_id = ?
GROUP BY path
ORDER BY views DESC, path
LIMIT 1000",
)?;
let rows = statement.query_map(params![tenant_id], |row| {
Ok(PageStat {
path: row.get(0)?,
views: row.get(1)?,
average_ms: row.get(2)?,
})
})?;
let stats = rows.take(limit).collect::<duckdb::Result<Vec<_>>>()?;
Ok(stats)
})
.await
}
}
Points that matter:
- Parameters, never formatted SQL. Every value from a request goes in as
a
?parameter (params!); SQL text is a constant of the application. A table or column the user chooses is picked from a fixed list, not interpolated. - A row cap in SQL and in Rust.
LIMIT 1000bounds what the engine produces andtake(limit)what the application materializes. - A time limit.
spawn_blockingwork cannot be cancelled, so the timeout calls DuckDB’sInterruptHandle, which makes the running query fail. The handle belongs to the connection, not to one query: if the timeout fires while the task is still waiting for the lock, it interrupts whichever query holds the connection at that moment. SizeQUERY_BUDGETfor the slowest legitimate report, or give each report its own connection (below). - Bounded resources.
max_memoryandthreadskeep DuckDB from taking the whole machine from the web server in the same process. - One connection serializes queries. For concurrent reports, open a
connection per worker with
Connection::try_clone(a new connection to the same database), each behind its own mutex, instead of sharing one.
Read-only dashboards and external files
A process that only reads a file another job writes opens it read-only; several read-only processes can then share the file, as long as no process holds it for writing:
use duckdb::{AccessMode, Config, Connection};
let config = Config::default()
.access_mode(AccessMode::ReadOnly)?
.enable_external_access(false)?;
let connection = Connection::open_with_flags("/app/data/analytics.duckdb", config)?;
enable_external_access(false) stops SQL from reaching state outside the
database, such as other files through read_csv, read_parquet or COPY,
and from installing or loading extensions. Leave it on only where the
application queries Parquet or CSV files itself, and then build those paths
from a fixed directory, never from request input.
Tests
Unit tests use MemoryAnalytics, as in the doctest above. DuckDB itself needs
no container: test DuckDbAnalytics against an in-memory database, and check
that it and the fake agree, so the fake keeps the report’s semantics. Engine
code:
#[cfg(test)]
mod duckdb_tests {
use super::*;
#[tokio::test]
async fn duckdb_report_matches_the_fake() -> Result<(), AnalyticsError> {
let duckdb = DuckDbAnalytics::in_memory().await?;
let fake = MemoryAnalytics::default();
for (tenant_id, path, duration_ms) in [
("acme", "/pricing", 100),
("acme", "/pricing", 200),
("acme", "/docs", 50),
("globex", "/pricing", 999),
] {
let view = PageView { tenant_id: tenant_id.into(), path: path.into(), duration_ms };
duckdb.record(view.clone()).await?;
fake.record(view).await?;
}
assert_eq!(duckdb.top_pages("acme", 10).await?, fake.top_pages("acme", 10).await?);
assert_eq!(duckdb.top_pages("acme", 1).await?.len(), 1);
Ok(())
}
}
With the optional analytics feature above, gate this module with
#[cfg(all(test, feature = "analytics"))] and run it in the CI job that
builds the engine.
Migrating from DuckDbStore
Up to 13.0.0-alpha.4, rullst-orm’s duckdb feature (orm-duckdb on
rullst) provided a generic analytics API. 13.0.0-alpha.5 removed the feature
and these types; each has a direct replacement in the duckdb crate:
| Removed | Replacement |
|---|---|
DuckDbStore::open(path), DuckDbStore::in_memory() | DuckDbAnalytics::open/in_memory above: Connection::open_with_flags or Connection::open_in_memory on the blocking pool, behind a mutex |
AnalyticsRepository::execute(sql, parameters) | connection.execute(sql, params![...]) inside run |
AnalyticsRepository::query(sql, parameters, limit) | connection.prepare(sql)?.query_map(params![...], ...) with a LIMIT and take(limit), decoding each row into the application’s own struct |
AnalyticsRow (columns by name) | row.get::<_, T>(index) or row.get::<_, T>("column") into a typed struct |
AnalyticsValue (parameters and results) | Typed parameters (String, i64, f64, bool, Vec<u8>, …) through ToSql/FromSql, or duckdb::types::Value for dynamic values |
AnalyticsTimeUnit | duckdb::types::TimeUnit, as in Value::Timestamp(TimeUnit::Microsecond, value) |
QueryLimit (1 to 10,000 rows) | A constant cap of your own (MAX_REPORT_ROWS), applied in SQL and with take |
The adapter also refused SQL text over 1 MiB, more than 1,024 parameters and
more than 8 MiB of parameter data. With constant SQL and typed parameters, as
above, those bounds have nothing left to check; validate the size of any
request input that becomes a parameter. The adapter’s source, which you may
copy under its MIT licence, is
rullst-orm/src/polyglot/duckdb.rs at v13.0.0-alpha.4.
To move:
- Remove
orm-duckdbfrom therullstfeatures (orduckdbfrom therullst-ormfeatures) and add theduckdbdependency shown above.cargo rullst upgradereports both the feature and the code that names the removed types. - Replace each
executeandquerycall with a method of an application trait likePageAnalytics, implemented as above. - Keep the data: a file the adapter wrote is an ordinary DuckDB database.
alpha.4 required
duckdb1.10506.1 (DuckDB 1.5.6) or a later 1.x release, so the application’sCargo.locknames the DuckDB release that wrote it; read DuckDB’s storage-compatibility notes before opening the file with a different DuckDB release, and back it up first. TheDUCKDB_PATHline thatcargo rullst new --duckdbwrote to.envkeeps working withanalytics_path.