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

Configuration

There are two kinds of settings:

  • Server configuration, read at startup: where the database is, where files go, limits. Changing it needs a restart. It’s described on this page.
  • Site settings, stored in the database and changed while the site runs: the site’s name, registration, the approval queue, the default blacklist. Change them under Admin → Settings or with moekura admin settings.

Where server configuration comes from

Each layer overrides the one before:

  1. built-in defaults,
  2. moekura.toml in the working directory, or the file given with --config <path> or MOEKURA_CONFIG,
  3. environment variables.

Every key has an environment variable MOEKURA_<SECTION>__<KEY> (two underscores), for example MOEKURA_DATABASE__URL or MOEKURA_STORAGE__S3__BUCKET. Lists are written as TOML, e.g. MOEKURA_SERVER__TRUSTED_PROXIES='["10.0.0.0/8"]'. Unknown keys are refused, so a typo fails loudly instead of being ignored.

moekura check-config validates the configuration and prints the result with credentials replaced by REDACTED: passwords and secret keys, the cookies, query values and headers of [sources.logins], and the user, password and query values of every address (the OTLP collector, the tagger’s model, …). Names stay, so it still shows what is sent where.

[server]

KeyDefaultMeaning
bind"0.0.0.0:8080"address the HTTP server listens on
public_url"http://localhost:8080"the address people use; set it to your https:// URL (cookies become Secure, forms are only accepted from this origin, and passkeys belong to its host)
trusted_proxies[]reverse proxies allowed to report the client’s address in X-Forwarded-For (addresses or CIDR ranges); see Behind a reverse proxy
request_timeout_secs30requests running longer are stopped with a 408
api_requests_per_minute300API requests a client may make a minute on average (per account, or per address for visitors); 0 for no limit
api_burst60how many API requests may come at once before the per-minute rate applies

Passkeys and public_url

Passkeys need no settings of their own: they are made for the host name in public_url (their relying party ID), and only work on pages from its origin. If the site moves to another domain, every passkey stops working, and people log in with their password (or single sign-on) and add new ones; a reverse proxy redirecting the old domain doesn’t change that. Passkeys are off when public_url names an IP address rather than a domain, since browsers don’t allow them there; http://localhost works for development.

[server.cors]

Which other websites’ scripts may call the API (/api/v1 and the Danbooru-compatible API) from a browser. Pages and forms are never available to other websites.

KeyDefaultMeaning
allowed_origins[]origins such as "https://app.example.com" (scheme, host and port, no path), or ["*"] for any website
allow_credentialsfalselet the listed origins send the visitor’s login cookie; without it, cross-origin requests count as a visitor’s unless they carry an API key. Needs explicit origins, not "*"
max_age_secs600how long browsers may remember a preflight answer
[server.cors]
allowed_origins = ["https://viewer.example.com", "http://localhost:5173"]

[server.connections]

Limits on the connections the app serves, so clients that open them and send nothing, send their requests a byte at a time, or stop reading the responses they asked for, can’t hold them for long or run the process out of file descriptors.

KeyDefaultMeaning
max512connections served at once; more wait to be accepted until one closes. Each takes a file descriptor, so keep it well under the process’s open file limit (ulimit -n, often 1024), which also covers database connections, files and media tools
idle_timeout_secs10a connection is closed when it goes this long without sending a whole request’s headers: one that sends nothing, sends its headers too slowly, or sits idle between requests. A request in progress is answered first
send_timeout_secs60a connection being closed (as idle, or because the app is stopping) is cut off when the client takes none of its response for this long, while no request is still being worked on: a client that stops reading, or never lets an HTTP/2 response through, can’t keep it. A slow download goes on as long as the client keeps taking some of it

These hold whether or not a reverse proxy is in front. Stopping the app waits for the responses in progress, but no longer than send_timeout_secs for a client that takes nothing. The limits don’t tell one client from another: a client opening connections fast enough can still fill them all, and others then wait, and one that keeps sending something, or takes a little of a response now and then, keeps its connection. A reverse proxy in front can limit connections per client (nginx’s limit_conn) and has its own client timeouts, which is one more reason to keep the app’s port reachable only by the proxy. A proxy that keeps connections to the app open between requests should let idle ones go sooner than idle_timeout_secs (Caddy’s keepalive transport option, nginx’s keepalive_timeout in an upstream block), or a request may now and then be sent on a connection the app is closing.

[database]

KeyDefaultMeaning
url(required)the primary’s connection URL
replicas[]read replicas’ URLs, used for searches and listings
max_connections16per pool (the primary and each replica)
min_connections0
acquire_timeout_secs5how long to wait for a free connection
statement_timeout_ms30000server-side limit per statement; 0 for none
auto_migratetruemigrate on start; with several servers, set false and run moekura migrate when deploying
replica_max_lag_secs10replicas further behind are skipped until they catch up; also how long someone’s reads stay on the primary after they change something

[auth]

KeyDefaultMeaning
session_idle_days30a login ends after this many days unused…
session_max_days365…or this long after logging in, however active

[auth.oidc]

Lets people log in through an OpenID Connect provider (single sign-on): Authentik, Keycloak, Kanidm, Zitadel, Google and others. Leave the section out to turn it off.

KeyDefaultMeaning
issuer(required)the provider’s issuer URL, which describes itself at /.well-known/openid-configuration under it; https://, or http:// on the same machine
client_id(required)from registering Moekura with the provider
client_secret(empty)likewise; empty for a public client
button_label"Log in with single sign-on"the button on the login page
scopes["openid", "email", "profile"]must include openid

Register the redirect URI https://your.site/login/oidc/callback (from server.public_url) with the provider. Logins use the authorization code flow with PKCE, and each one has to finish in the browser that started it (a short-lived cookie ties them together). The ID token’s signature isn’t checked, since it comes straight from the provider, so the provider is only ever reached over https: its description must list https:// login and token endpoints, and redirects to plain http are refused. Plain http is allowed only for a provider on the same machine, for development.

Someone logging in through the provider for the first time gets a new account (with no password) when registration is open, or one waiting for approval when it’s approval; with invite or closed, only people who linked an existing account can. A new account takes its name from the provider (the next free one if it’s taken), and the provider’s email address if it says it’s verified, nobody here uses it yet, and the site accepts its domain. Signing up this way counts towards the limit of new accounts per address, like the sign-up form, and a network ban keeps the network from signing up or logging in this way, as from the forms. Where new accounts confirm their address (Admin → Settings → Registration), they need an address the site accepts: one the provider says is verified is good enough; otherwise a confirmation link is sent to it first, and without one, signing up through the provider is refused. The captcha isn’t asked for, as the provider has already checked who is logging in.

[auth.captcha]

A captcha service for the sign-up form and new accounts’ comments: where it’s asked for is chosen under Admin → Settings (nowhere, until then). Logging in to an account also asks for it while someone guesses the account’s password from many networks at once. Leave the section out to turn it off.

KeyDefaultMeaning
provider(required)"turnstile" (Cloudflare Turnstile) or "hcaptcha"
site_key(required)the public key the provider gives you
secret_key(required)the private key tokens are checked with
verify_url(the provider’s)where tokens are checked, for a proxy or a compatible service

The page asking for it loads the provider’s script and frame, which the content security policy then allows from the provider’s origin.

[cache]

KeyDefaultMeaning
backend"memory"where rate limit counters and cached search counts live: "memory" (search counts and the API’s per-request limit in each process, the other rate limits in the database, shared by every web server) or "valkey" (all shared by every web server)
url(unset)for valkey: redis://host:6379, or rediss:// for TLS; Redis and other compatible servers work too
count_ttl_secs30how long a search count that reached search.count_limit (“10,000+”) is reused; 0 turns this off
prefix"moekura"starts every key stored in Valkey; give sites that share a server different prefixes

If Valkey (or, without it, the database) stops answering, each server counts rate limits on its own and stops caching until it’s back, and logs a warning; nothing fails.

[jobs]

KeyDefaultMeaning
workers2background jobs processed at once, per process
run_in_servetruealso run workers inside serve; set false when you run moekura worker separately
lock_timeout_secs300a job whose worker stopped responding is retried after this

[mail]

Outgoing mail over SMTP, for email verification and password resets, and to warn users about wrong two-factor codes and about someone trying to use their address. Messages are sent by the job workers, so a slow mail server doesn’t hold up the site, and failed sends are retried.

KeyDefaultMeaning
host(empty)the SMTP server; empty turns mail off, along with the features that need it
tls"starttls""starttls" (upgrade a plain connection; required), "tls" (TLS from the start) or "none" (only for a relay on the same machine or network)
port(by tls)587 for starttls, 465 for tls, 25 for none
username, password(empty)the login, if the server needs one
from(empty)the sender, as address@example.com or Site name <address@example.com>; required with host
timeout_secs30connecting or sending one message gives up after this

Check the settings with moekura admin send-test-mail you@example.com, which sends straight away and prints any error.

The first three are defaults: the site settings’ Search pages (pagination) override each of them while the site runs, on every server, without a restart. See Search pages.

KeyDefaultMeaning
per_page40posts per page
max_per_page200the most limit: may ask for
max_page1000deepest numbered page; “next” links keep working beyond it
max_terms40most tags and filters in one search; every search is also at most 1000 words and 10,000 characters long, whatever this is
wildcard_limit100most tags a wildcard expands to (the most used)
count_limit10000result counts are exact up to this, estimated above
count_cost_limit25000counts PostgreSQL expects to cost more than this (roughly pages read) are estimated instead, so filters no index covers don’t read every post

[storage]

KeyDefaultMeaning
backend"local""local" (a directory) or "s3"
path"data"the directory, for local
public_base_url(unset)where browsers load files from, e.g. a CDN; unset, the app serves them under /data/

[storage.s3]

KeyDefaultMeaning
bucket""
region"us-east-1"
endpoint(unset)for MinIO, Garage, R2, B2 and others; unset for AWS
access_key_id, secret_access_key""empty to use AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY or instance credentials
path_stylefalseput the bucket in the path; most self-hosted stores need this

See File storage.

[media]

KeyDefaultMeaning
max_upload_mb100largest upload
max_link_upload_mbmax_upload_mblargest file downloaded from a pasted link or a remote booru import
max_pixels200000000larger images are refused before decoding
max_duration_secs600longest video
allowed_types["jpeg", "png", "gif", "webp", "avif", "mp4", "webm", "ugoira"]ugoira is Pixiv’s zip of animation frames; add "jxl" for JPEG XL (off by default: libvips doesn’t consider its decoder hardened against malicious files). MP4 may hold H.264, HEVC, VP9 or AV1 video with AAC, MP3 or Opus audio; WebM, VP8, VP9 or AV1 with Opus or Vorbis. QuickTime and other Matroska files are refused
thumbnail_sizes[250, 500]thumbnail boxes, 1x and 2x for high-density screens
sample_size1600larger images also get a resized copy for the post page
variant_format"webp""webp" or "avif" (smaller, slower) for thumbnails and samples
tool_timeout_secs120longest a media tool may run
strip_metadata"strip"remove identifying metadata (EXIF and GPS, XMP, IPTC, comments) from uploaded originals too: "strip" (JPEG, PNG and WebP; other types, such as GIF, AVIF, JPEG XL and videos, keep theirs), "require" (and refuse other types) or "off" (originals kept exactly as uploaded); see File metadata. Up to 0.5 the default was "off"
max_tool_processes0media tools (vips, ffmpeg, …) running at once in one serve or worker process, uploads and jobs together; more wait their turn. 0: one per CPU core
ffmpeg_threads2threads each ffmpeg run may use for decoding, filters and encoding; 0 lets ffmpeg pick (about one per core)
ffmpeg_memory_mb2048memory each ffmpeg or ffprobe run may use; 0 for no limit, otherwise at least 512 (Linux only)
ffmpeg_cpu_secs0CPU time each ffmpeg or ffprobe run may use, all threads together; 0 for no limit (Linux only)
vips_memory_mb4096memory each vips, vipsheader or vipsthumbnail run may use; 0 for no limit, otherwise at least 512 (Linux only)
vips_cpu_secs0CPU time each vips, vipsheader or vipsthumbnail run may use; 0 for no limit (Linux only)
work_dirsystem temp dirscratch space for uploads and processing; an upload’s scratch files left behind for more than a day (by a restart, say) are removed at startup and every hour, so several processes can share it

Limits on media tools

Files are decoded by vips, ffmpeg and ffprobe in their own processes, so a hostile or broken file costs at most one of those, never the server. Each run is stopped after tool_timeout_secs, and at most max_tool_processes run at once. ffmpeg also uses at most ffmpeg_threads threads, so one video can’t take every core.

On Linux, ffmpeg and ffprobe are also held to ffmpeg_memory_mb and ffmpeg_cpu_secs, and the libvips tools (vips, vipsheader, vipsthumbnail) to vips_memory_mb and vips_cpu_secs, set with ulimit by /bin/sh before they start. The memory limits are on address space, which counts the program’s libraries and thread stacks too, so they’re well above what the process really uses; ffmpeg and libvips each need a few hundred MB of it to start. Decoding the largest pictures max_pixels allows (a progressive JPEG or an AVIF of 200 megapixels) takes about 4 GB; with a lower max_pixels, vips_memory_mb can be lower too. A file that would need more is refused with an explanation (“too demanding to process”) rather than as an error on the site’s side: on upload, or in the failed job’s message when thumbnails are made. The tools don’t always say an allocation failed, so some such files are reported as damaged instead. Without a CPU limit, an ffmpeg run still can’t use more than ffmpeg_threads × tool_timeout_secs of CPU time, and a libvips run, which works on one thread, about tool_timeout_secs. Other systems ignore these limits.

These limits are per process. A container’s memory limit (Docker mem_limit, or the cgroup a service runs in) counts the real memory of the server and every tool running at once; when it’s reached, the kernel stops whichever process it picks, possibly the server. On a small machine, keep max_tool_processes low (1 or 2 on 1 GB) so tools fit beside the server, and let ffmpeg_memory_mb and vips_memory_mb stop single runs that grow too large.

[media.tools]

Paths to vips, vipsheader, vipsthumbnail, ffmpeg and ffprobe, if they aren’t on PATH.

[paths]

KeyMeaning
templates_overridea directory whose files replace built-in templates with the same path, e.g. base.html
static_overridethe same for static files, e.g. css/main.css; also where themes are added
locales_overridetranslations: a directory per language (de/*.ftl), adding languages or replacing built-in messages

[tagger]

The optional tagger, which suggests tags for new uploads.

KeyDefaultMeaning
enabledfalsequeue new uploads for moekura tagger; set it for every process
model"wd-vit-tagger-v3"wd-vit-tagger-v3, wd-convnext-tagger-v3, wd-swinv2-tagger-v3, wd-eva02-large-tagger-v3, or "custom"
model_url, tags_urlunsetfor custom: the ONNX model and its selected_tags.csv
model_sha256, tags_sha256unsetfor custom: their SHA-256 checksums
model_dir"data/models"where models are downloaded to, one directory each
runtimeORT_DYLIB_PATH, or the system’sthe ONNX Runtime library, libonnxruntime.so
threads0threads one image uses; 0 means one per core
workers1posts tagged at once
account"tagger"who automatically applied tags are credited to; created without a password when moekura tagger starts, and nobody can sign up with the name

[telemetry]

KeyDefaultMeaning
log_format"text""text" or "json"
log_filter"info,sqlx::postgres::notice=warn,ort=warn"a tracing filter; RUST_LOG overrides it ("info,tower_http=debug" logs every request)
metrics_bindunsetwhere serve and worker serve Prometheus metrics at /metrics, e.g. "127.0.0.1:9100"; unset, nothing is collected
otlp_endpointunsetan OpenTelemetry collector’s OTLP/HTTP address, e.g. "http://otel-collector:4318"; traces go to its /v1/traces
otlp_sample_ratio1.0the share of requests and jobs traced, from 0.0 to 1.0
service_name"moekura"service.name on exported traces

Metrics

With metrics_bind set, moekura serve and moekura worker each open a second listener serving /metrics in the Prometheus text format. It is separate from the site so it is never reachable through the reverse proxy: bind it to loopback or a private address, and keep it off the internet with a firewall. It has no authentication of its own. The address must differ from server.bind, and processes on the same machine need different ports.

MetricLabelsMeaning
moekura_http_requests_totalmethod, route, statusrequests answered
moekura_http_request_duration_secondsmethod, routehistogram of how long they took
moekura_http_requests_in_flightrequests being answered now
moekura_jobs_finished_totalkind, resultjobs run: done, retry (failed; retried while attempts remain), failed (could never succeed) or panicked
moekura_job_duration_secondskindhistogram of how long they ran
moekura_jobskind, statejobs ready (due now), scheduled (for later), running and dead
moekura_jobs_oldest_ready_secondskindhow long the longest-waiting due job has waited
moekura_db_connectionspool, stateconnections idle and in_use, for primary and each replica_N
moekura_db_connections_maxpooleach pool’s limit

route is the route’s template, such as /posts/{id}, or unmatched for requests that matched none, so the number of series stays small whatever is requested. No label carries a user, address, tag or query. The queue and pool gauges are read when Prometheus scrapes; the queue counts all processes’ jobs, so scrape it from one of them.

A growing moekura_jobs_oldest_ready_seconds means the workers are behind; a climbing dead count, that jobs are failing for good (see Background jobs).

Grafana dashboard

deploy/grafana/moekura.json is a Grafana dashboard for these metrics: requests by route and status, latency, the job queue and how jobs end, and the database pools. Import it in Grafana (Dashboards → New → Import) and pick your Prometheus data source; it needs Grafana 10.4 or later. Its Job and Instance selectors choose which scraped processes it shows, and Route and Job kind narrow the HTTP and job panels.

Traces

With otlp_endpoint set, each request and job is a trace, with the spans logged inside it, sent in batches over OTLP/HTTP (protobuf) to an OpenTelemetry collector, which can pass them to Jaeger, Tempo or another tracing backend. Spans carry the moekura.role of the process (serve, worker, tagger, migrate) and its version. log_filter decides which spans exist, as for logs. Traces still buffered are sent when the process shuts down cleanly.

The endpoint must be http or https; no credentials are sent, so put a collector next to moekura rather than sending to a hosted service directly. A busy site can lower otlp_sample_ratio: a sampled request traces everything beneath it.

[sources]

KeyDefaultMeaning
loginsnonelogins for sites that show some works only to members, by domain
x.fxembed_api_url"https://api.fxtwitter.com"the API of an FxEmbed instance that posts on X are read through; empty to not use one

Each [sources.logins."<domain>"] covers the domain and its subdomains and can set any of:

KeyMeaning
cookiethe Cookie header, "name=value; other=value"
queryparameters added to the address, such as an API key
headersother headers, such as Authorization

They’re sent only to that site, over https, when reading where an upload comes from, and not along redirects to other sites; the files themselves are downloaded without them.

[webhooks]

KeyDefaultMeaning
allow_private_addressesfalselet webhooks go to private, loopback and link-local addresses (a service on the same machine or network)
timeout_secs10how long a delivery may take
max_concurrent1deliveries sent at once, across all job workers; the rest wait their turn, so receivers that don’t answer can’t hold every worker (keep it below jobs.workers)

Discord webhooks are public addresses, so they work without allow_private_addresses.

Search pages

How many posts a search shows and how deep its numbered pages go is decided, for each limit, by the first of these that is set:

  1. the site setting, under Admin → Settings → Search pages or moekura admin settings set pagination '{"per_page": 60, "max_per_page": 100, "max_page": 500}' (leave a key out, or blank on the form, to fall back),
  2. [search] in the server configuration,
  3. the built-in default.

A user’s own page size (in their settings) replaces the posts per page for their searches, but never goes over the largest page; neither does a search’s limit:, nor limit= in the APIs. Searches through the site, /api/v1 and the Danbooru-compatible API all follow the same limits (Danbooru apps get 20 posts unless they ask for more, as on Danbooru). Past the deepest numbered page, “next” links (page=b<id>) keep going. moekura check-config shows only the server configuration’s values; moekura admin settings shows the site settings.