Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

DuckDB + Quack + Caddy + R Setup on the Homelab

I really like DuckDB database engine. Pretty much all the data work I do for personal projects I do with DuckDB as my database. Recently, v2.0.0 of DuckDB has been released which now allows to run DuckDB as a remote service to which other DuckDB instances can connect. I have spent half my weekend to setup such service on my homelab box which is a Lenovo miniPC with 8GB of RAM and 500GB of hard disk.

Initial Homelab Setup

I will describe this at one point when the config is final. For now, I have set up a Wireguard tunnel between the homelab and my laptop, cutting out all other inbound connections. Both my Homelab and my laptop are running Debian so the below should be adjusted to your OS.

Setup Architecture

If you want to work with remote DuckDB over the Internet, this setup needs to be enhanced with additional security measures and HTTPS

The idea of the DuckDB setup is as follows:

  • Server Side: Homelab box: a running DuckDB process that has started a Quack listener with a secret token. This opens up tables and files related to DuckDB over the network and makes them reachable
  • Reverse Proxy: Caddy: caddy is my favourite web server these days. In this setup caddy will serve as a reverse proxy in front of DuckDB-Quack service. Since my Homelab box is denying all incoming requests except from my machine and only through Wireguard tunnel, caddy will only handle HTTP requests from and to Quack.
  • Client Side: R: Once everything on Homelab is set up, I will connect to it from R session.

The final state is data is stored on my Homelab as parquet files, views and tables, if needed, are created from R and everything is stored in a catalogue DuckDB file.

laptop (R + duckdb) │ Quack over Wireguard, port 8494 ▼ homelab: ufw → Caddy (LAN-facing) │ plain HTTP, loopback only, Caddy redirects from Wireguard to localhost:9494 ▼ homelab: DuckDB process (127.0.0.1:9494) │ reads ▼ homelab: /srv/duckdb/data/*.parquet (+ a .duckdb file)

Prerequisites

You need to check DuckDB versions in three places - make sure version is 2.0.0:

  • on server - duckdb --version. If DuckDB is not installed, refer to the docs for instructions
  • on laptop - duckdb --version
  • check R package version with packageVersion("duckdb"). If needed, update it with update.packages("duckdb").

One important caveat here. By default, DuckDB will be installed in the $HOME of whoever runs the command. What you mind need to do is to copy duckdb binary to /usr/local/bin so that it could be run by anyone with necessary rights:

sudo install -o root -g root -m 755 "$(command -v duckdb)" /usr/local/bin/duckdb

Data On Server

Copy parquet files to the server with rsync or however you do that. You can use JSON files too it does not change the rest of the process. I have put my data files into /srv/duckdb/data on my Homelab.

Setup DuckDB

There are a couple of steps involved here.

Dedicated User

As always, having a dedicated user with limited rights is a good idea. A few considerations:

  • duckdb user does not need home directory and a shell, so that no secrets are saved in the home directory and no interactive shell session exists
  • duckdb user should be able to run services and has its own group
  • duckdb user should not have a password and account must be locked
  • dedicated duckdb group will allow to share access to data directory without changing directory’s permissions

On the server you can do it as follows:

sudo useradd --system --user-group --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin duckdb # creates a user
sudo install -d -o duckdb -g duckdb -m 750 /srv/duckdb

Now you need to be able to copy files from your laptop to your server and to the folder that duckdb user owns. On the server:

sudo usermod -aG duckdb <youruser> # this adds youruser to duckdb group
sudo chmod 2770 /srv/duckdb/data # 2 is a setgid bit which allows files in the directory inherit directory's group so that duckdb can read whatever your user has dropped there

Secret Token

From official Quack docs:

A Quack server exposes the full SQL surface of the underlying DuckDB instance, including read and write access to every table the server’s session can see. Because of > this, the extension ships with conservative defaults that prevent accidental exposure:

  • The server requires an authentication token, which the client has to supply on every connection. Unless a token is passed explicitly or supplied by a quack secret, the server generates a random token at startup.
  • The server binds to localhost only, non-local hostnames require an explicit allow_other_hostname = true.
  • The server does not use TLS for local URIs, as TLS for localhost communication only adds dependencies for no real benefit. Non-local URIs default to HTTPS with a self-signed certificate (see quack_serve parameters).

This means that in order for the whole setup to work permanently without reentering automatically generated tokens every time you need to have a secret token both on the server and on the laptop that Quack knows about and can use in communication.

To avoid secret token appearing in shell history or tmux scrollback, we need to generate it directly into the file. On the server:

sudo sh -c 'umask 077; openssl rand -hex 32 > /etc/duckdb-quack.token'

The file with generated token is only accessible by root, later, when creating a service for duckdb this file will be read from a private, in-memory path only this process can see. openssl rand draws from kernel’s CSPRNG and -hex allows to avoid characters that might break quoting in SQL strings, R strings or shell commands.

Now, we need to pass that secret token to the laptop. I use pass utility to manage secrets on my laptop. If you don’t have it installed:

sudo apt update && sudo apt upgrade -y
sudo apt install pass

To pass the token from server directly to laptop we can do this on the server:

sudo install -o "$USER" -m 600 /etc/duckdb-quack.token ~/quack.tmp # to create a temporary copy of the file with token so that your user could access it via SSH

Now on the laptop:

ssh <your-server> 'cat ~/quack.tmp' | pass insert -m duckdb/quack-token # get that token file and pass it directly to pass, token is not visible to anything

If successful, you can destroy your copy of the token file on the server:

shred -u ~/quack.tmp

You can manually check if token from the server matches the one on the laptop:

pass show duckdb/quack-token | sha256sum # on laptop
sudo sha256sum /etc/duckdb-quack.token # on the server

Systemd Unit

Now you need to setup a systemd service on the server that would run DuckDB process + you need to create an init script that would start the Quack server with required parameters. The init script can look like this:

SET extension_directories = ['/srv/duckdb/extensions'];
SET memory_limit = '4GB';

SET VARIABLE quack_token = (
    SELECT trim(content, chr(10) || chr(13) || ' ')
    FROM read_text(getenv('CREDENTIALS_DIRECTORY') || 'quack_token')
);

CALL quack_serve('quack:127.0.0.1', token = getvariable('quack_tokoen'));

Now the service unit file for systemd:

[Unit]
Description=DuckDB Quack server
After=network.target

[Service]
Type=simple
User=duckdb
Group=duckdb
LoadCredential=quack-token:/etc/duckdb-quack.token
ExecStart=/bin/sh -c 'sleep infinity | exec /usr/local/bin/duckdb /srv/duckdb/catalog.duckdb -init /etc/duckdb/serve.sql'
Restart=on-failure
RestartSec=5

# Sandboxing
NoNewPrivileges=yes
ProtectSystem=strict
ReadWritePaths=/srv/duckdb
ProtectHome=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX

[Install]
WantedBy=multi-user.target

A couple of comments on what those lines do:

  • After=network.target, not network-online.target: DuckDB only binds loopback, so it doesn’t need to wait for the LAN or the tunnel to be up.
  • Restart=on-failure: if DuckDB crashes, systemd restarts it after 5 seconds. A clean stop stays stopped.
  • NoNewPrivileges: the process can never gain privileges, for example through setuid binaries.
  • ProtectSystem=strict: the whole filesystem becomes read-only for this service. ReadWritePaths then opens just /srv/duckdb. A compromised DuckDB can’t modify anything else on the system, even files the duckdb user would normally be allowed to write.
  • ProtectHome: /home is invisible to the service.
  • PrivateTmp: the service gets its own private /tmp.
  • PrivateDevices: no access to hardware devices.
  • ProtectKernel and ProtectControlGroups: kernel settings, kernel modules, and cgroups are off-limits.
  • RestrictAddressFamilies: only IP and Unix sockets are allowed. This blocks raw packet sockets and other exotic socket types an attacker might want.

Now bring up the new service:

systemd-analyze verify duckdb-quack.service
sudo systemctl daemon-reload
sudo systemctl enable --now duckdb-quack.service
sudo journalctl -u duckdb-quack -f # to check the logs after service start, shouldn't show any errors
ss -tlnp | grep 9494 # should show 127.0.0.1 only

Checks

You can now check how systemd will run it:

sudo -u duckdb sh -c 'sleep infinity | CREDENTIALS_DIRECTORY=/tmp/credtest /usr/local/bin/duckdb /srv/duckdb/catalog.duckdb -init /etc/duckdb/serve.sql'

It should output something like this:

-- Loading resources from /etc/duckdb/serve.sql

┌─────────────────┬───────────────────────┬────────────┐
│   listen_uri    │      listen_url       │ auth_token │
│     varchar     │        varchar        │  varchar   │
├─────────────────┼───────────────────────┼────────────┤
│ quack:localhost │ http://localhost:9494 │ NULL       │
└─────────────────┴───────────────────────┴────────────┘

Caddy

To install caddy check their installation instructions. Installation should give you all you need to run a caddy server:

  • caddy system user
  • systemd unit
  • /etc/caddy/Caddyfile
  • /var/log/caddy/ for logs

For my setup I opt out of HTTPS and I connect to my Homelab via Wireguard tunnel, so my Caddyfile looks something like this:

http://10.0.0.1:8494 {
	bind 10.0.0.1

	reverse_proxy 127.0.0.1:9494 {
		flush_interval -1
	}

	request_body {
		max_size 256MB
	}

	log {
		output file /var/log/caddy/quack-access.log
		format json
	}
}

This is mostly what DuckDB docs suggest for a minimal config:

  • flush_interval -1: Quack streams large results as a series of FETCH responses instead of being buffered in Caddy.
  • request_body: requests can carry long SQL or inserted data, which can exceed the default body size limit.
  • logs: a separate JSON log just for Quack traffic, it is optional, you can use default log file name.

This is optional because I will use Wireguard tunnel. You need to tell caddy service that it depends on wireguard tunnel:

sudo systemctl edit caddy

then

[Unit]
Wants=wg-quick@wg0.service # or whatever you wireguard tunnel service is called
After=wg-quick@wg0.service # makes starting Caddy also pull in the tunnel

Now apply caddy config:

caddy fmt --overwrite /etc/caddy/Caddyfile
caddy validate --config /etc/caddy/Caddyfile
sudo systemctl reload caddy

and check caddy serves on correct (wireguard in my case) IP:

ss -tlnp | grep 8494 # this should show your wireguard IP and correct port

Testing

We should be able to connect to Quack from the laptop now. Quack exposes whoami() table macro that surfaces basic identity and runtime info, which is useful for testing purposes:

QUACK_TOKEN="$(pass show duckdb/quack-token)" duckdb -c "
SET VARIABLE t = getenv('QUACK_TOKEN');
FROM quack_query('quack:10.0.0.1:8494', 'FROM whoami()', token = getvariable('t'), disable_ssl = true);
"

Make sure to run QUACK_TOKEN=... and duckdb -c ... on one line. If you run export QUACK_TOKEN=..., token can be exposed. The successful result will look like this (this is from Quack docs):

┌─────────┬──────────┬──────────┬─────────┬─────────────────┬───────────────────────────────┬────────────────────────────────────────────────────┐
│  name   │ provider │ hostname │ region  │     uptime      │            ts_now             │                        meta                        │
│ varchar │ varchar  │ varchar  │ varchar │    interval     │   timestamp with time zone    │                        json                        │
├─────────┼──────────┼──────────┼─────────┼─────────────────┼───────────────────────────────┼────────────────────────────────────────────────────┤
│ NULL    │ NULL     │ NULL     │ NULL    │ 00:04:56.832456 │ 2026-10-21 15:59:38.631715+02 │ {"duckdb_version":"v2.0.0","platform":"osx_arm64"} │
└─────────┴──────────┴──────────┴─────────┴─────────────────┴───────────────────────────────┴────────────────────────────────────────────────────┘

Connect to Quack from R

This is the final step which has been the main goal all the way. Conceptually, the process looks like this:

  • Connect to Quack server with the secret token
  • ATTACH remote database
  • reference the remote database
  • build up the query
  • get the result of the query

There are other ways to approach this but this is how I use it mostly. Here is a sketch of the code:

library(DBI)
library(duckdb)
library(dplyr)
packageVersion("duckdb")

connect_homebox <- function(host = "10.0.0.1", port = 8494) {
  token <- system2("pass", c("show", "duckdb/quack-token"), stdout = TRUE)[1]
  con <- dbConnect(duckdb())
  dbExecute(con, sprintf(
    "ATTACH 'quack:%s:%d' AS homebox (TOKEN '%s', DISABLE_SSL true)",
    host, port, token
  ))
  con
}

con <- connect_homebox()

# Test with whoami() again to make sure connection works from R as well
dbGetQuery(con, "FROM homebox.query('FROM whoami()')")
# Test table
dbExecute(con, "
  CREATE OR REPLACE TABLE homebox.main.demo AS
  SELECT range AS id,
         now() - INTERVAL (random() * 365) DAY AS ts,
         (random() * 100)::INT AS value
  FROM range(1000000)
")

demo <- tbl(con, "homebox.main.demo")

q <- demo |>
  mutate(d = as.Date(ts)) |>
  count(d)

show_query(q) # this shows you the actual query that was used
res <- collect(q) # this fetches the actual results from remote database

# Cleanup at the end
dbDisconnect(con, shutdown = TRUE)

Coda

That is all there is to it. I must admit that I like these sorts of setups although they are not necessarily a practical need. I only have one homelab box and most of the data I work with I can fit on my laptop. However, this DuckDB-Quack combination allows me to keep data in one place and access it not only from R, but also write to it from my custom Go parser and read it from my local Observable Framework documents.

I had other plans for the weekend but this consumed all of my time which is so typical for me…

If you have comments or questions, you can ping me on Mastodon