Run the Loosen server
loosend is the self-hosted mode of Loosen: one static program (downloads for Linux, macOS and Windows, or a Docker image) that holds your catalogues in memory and answers the widget's explain requests. Use it for large catalogues. It needs a Business or trial licence. It uses only the Go standard library, speaks plain HTTP (put TLS in front), and never contacts us: the licence is checked offline.
Download and try it
Download the archive for your platform from the downloads page (Linux x86-64 and ARM64, macOS Intel and Apple silicon, Windows x86-64), check its checksum, set a few variables and start it. Your licence key is on your licence page; the public key that checks it is already built into the server, so there is nothing else to configure. Settings come from a JSON file (--config) and from environment variables, which override the file; the licence is best kept in the environment.
# 1. Download the archive for your platform and check it (Linux x86-64 here: the file names are on the downloads page)
curl -fsSLO https://loosen.sicena.com/downloads/loosend/v1/SHA256SUMS
curl -fsSLO https://loosen.sicena.com/downloads/loosend/v1/loosend-1.0.0-linux-amd64.tar.gz
sha256sum --check --ignore-missing SHA256SUMS
tar xzf loosend-1.0.0-linux-amd64.tar.gz && cd loosend-1.0.0-linux-amd64
# 2. Try it in this terminal
export LOOSEND_ADMIN_KEY="$(openssl rand -hex 24)" # keep it: it protects the admin API
export LOOSEND_ALLOWED_ORIGINS=https://www.example.com # the origin of the page that hosts the widget
export LOOSEND_LICENCE='LSN1....' # your licence key (from your licence page)
export LOOSEND_DATA_DIR=/var/lib/loosend # snapshots, so a restart keeps the catalogs
./loosend --addr 127.0.0.1:8080
SIGTERM and SIGINT shut it down gracefully: in-flight requests finish and a last snapshot is written. Logs are JSON on stderr. loosend --version prints the version and the commit it was built from.
Run it as a service
Every archive contains the files below in contrib/ form, and an INSTALL.md with the same steps. Put TLS in front (nginx, Caddy, your load balancer): the server speaks plain HTTP, and keep the admin API (PUT/POST/DELETE on /v1/catalogs...) off the internet; the browser only needs POST .../explain.
Linux (systemd)
sudo install -m 0755 loosend /usr/local/bin/loosend
sudo useradd --system --no-create-home --shell /usr/sbin/nologin loosend
sudo install -d -m 0750 -o root -g loosend /etc/loosend
sudo install -m 0640 -g loosend loosend.env.example /etc/loosend/loosend.env # edit: admin key, licence, origins
sudo install -m 0640 -g loosend loosend.json.example /etc/loosend/loosend.json # edit or replace: your catalogs
sudo install -m 0644 loosend.service /etc/systemd/system/loosend.service
sudo systemctl daemon-reload && sudo systemctl enable --now loosend
curl http://127.0.0.1:8080/health
The environment file (/etc/loosend/loosend.env), readable by the service user only:
# Environment of loosend (systemd EnvironmentFile; also fine for Docker --env-file). Keep this file readable by the service user only.
# Every setting here overrides the same setting in loosend.json.
# Required: protects the admin API (create catalogs, load items). 16+ characters, e.g. openssl rand -hex 24
LOOSEND_ADMIN_KEY=change-me-to-a-long-random-string
# Your licence key, from https://loosen.sicena.com (the licence page of your order). Without it: evaluation mode, 1000 items.
# A Starter licence is for the browser only; the server needs Business, trial or dev. No public key is needed: it is built in.
LOOSEND_LICENCE=
# The pages that may call explain from a browser (CORS allow-list), comma separated, no trailing slash.
LOOSEND_ALLOWED_ORIGINS=https://www.example.com
# Where snapshots are written (a restart reloads the catalogs from them). /var/lib/loosend is the systemd StateDirectory.
LOOSEND_DATA_DIR=/var/lib/loosend
# Behind a reverse proxy (nginx, Caddy, a load balancer): take the client IP from the last X-Forwarded-For entry.
# Leave it off when loosend is reached directly, or anybody can fake the header.
LOOSEND_TRUST_PROXY=false
# The listen address. Behind a reverse proxy on the same machine use 127.0.0.1:8080.
LOOSEND_ADDR=127.0.0.1:8080
The unit file (/etc/systemd/system/loosend.service): an unprivileged user, the usual hardening, a restart after a crash, a graceful stop, snapshots in /var/lib/loosend. Logs: journalctl -u loosend -f.
# systemd unit for loosend. Install:
# sudo install -m 0755 loosend /usr/local/bin/loosend
# sudo useradd --system --no-create-home --shell /usr/sbin/nologin loosend
# sudo install -d -m 0750 -o root -g loosend /etc/loosend
# sudo install -m 0640 -g loosend loosend.env.example /etc/loosend/loosend.env # then edit it (admin key, licence, origins)
# sudo install -m 0640 -g loosend loosend.json.example /etc/loosend/loosend.json # optional: catalogs, feeds, limits
# sudo install -m 0644 loosend.service /etc/systemd/system/loosend.service
# sudo systemctl daemon-reload && sudo systemctl enable --now loosend
# Logs: journalctl -u loosend -f (JSON lines)
[Unit]
Description=Loosen server (loosend)
Documentation=https://loosen.sicena.com/docs/server
After=network-online.target
Wants=network-online.target
[Service]
User=loosend
Group=loosend
EnvironmentFile=/etc/loosend/loosend.env
ExecStart=/usr/local/bin/loosend --config /etc/loosend/loosend.json
Restart=on-failure
RestartSec=2
TimeoutStopSec=30
# snapshots live in /var/lib/loosend (created by systemd, owned by the user above)
StateDirectory=loosend
StateDirectoryMode=0750
# hardening: loosend only needs the network and its state directory
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
PrivateDevices=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
RestrictNamespaces=true
LockPersonality=true
MemoryDenyWriteExecute=true
# a feed read from a local file: allow its folder, e.g. ReadOnlyPaths=/srv/export
[Install]
WantedBy=multi-user.target
macOS (launchd)
Edit the keys, then follow the commands at the top of the file: it installs a daemon under /Library/LaunchDaemons, readable by root only (it holds the keys), started at boot and restarted if it stops.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!-- launchd job for loosend on macOS. Install:
sudo install -m 0755 loosend /usr/local/bin/loosend
sudo mkdir -p /usr/local/var/loosend /usr/local/etc/loosend
(edit the keys below, then)
sudo install -m 0600 -o root com.sicena.loosend.plist /Library/LaunchDaemons/com.sicena.loosend.plist
sudo launchctl bootstrap system /Library/LaunchDaemons/com.sicena.loosend.plist
Stop / remove: sudo launchctl bootout system/com.sicena.loosend
The file holds secrets: keep it readable by root only (the install line above does that). -->
<plist version="1.0">
<dict>
<key>Label</key><string>com.sicena.loosend</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/bin/loosend</string>
<string>--config</string><string>/usr/local/etc/loosend/loosend.json</string>
</array>
<key>EnvironmentVariables</key>
<dict>
<key>LOOSEND_ADMIN_KEY</key><string>change-me-to-a-long-random-string</string>
<key>LOOSEND_LICENCE</key><string></string>
<key>LOOSEND_ALLOWED_ORIGINS</key><string>https://www.example.com</string>
<key>LOOSEND_DATA_DIR</key><string>/usr/local/var/loosend</string>
<key>LOOSEND_ADDR</key><string>127.0.0.1:8080</string>
</dict>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
<key>StandardErrorPath</key><string>/usr/local/var/log/loosend.log</string>
<key>StandardOutPath</key><string>/usr/local/var/log/loosend.log</string>
</dict>
</plist>
Windows
loosend.exe is a console program, not a native Windows service, so sc.exe create would not work (the service manager would stop it after 30 seconds). The built-in way is a scheduled task that starts at boot as SYSTEM and restarts after a failure. Put loosend.exe, loosend.json (optional) and the two files below in one folder (for example C:\loosend), edit run-loosend.cmd, and run install-task.ps1 in an elevated PowerShell. If you prefer a real service, wrap run-loosend.cmd with a service wrapper such as NSSM (a third-party tool; we do not ship it). We build and unit-test the Windows program but do not run a Windows server ourselves: tell us if a step does not work.
@echo off
rem Starts loosend with its settings. Edit the values, keep this file readable by administrators only.
rem Used by the scheduled task of INSTALL.md ("Windows"); you can also double-click it to try the server.
set LOOSEND_ADMIN_KEY=change-me-to-a-long-random-string
set LOOSEND_LICENCE=
set LOOSEND_ALLOWED_ORIGINS=https://www.example.com
set LOOSEND_DATA_DIR=C:\ProgramData\loosend\data
set LOOSEND_ADDR=127.0.0.1:8080
if not exist "%LOOSEND_DATA_DIR%" mkdir "%LOOSEND_DATA_DIR%"
"%~dp0loosend.exe" --config "%~dp0loosend.json" >> "C:\ProgramData\loosend\loosend.log" 2>&1
# Registers loosend as a scheduled task that starts at boot, runs as SYSTEM and restarts after a failure.
# Run in an elevated PowerShell, from the folder that holds loosend.exe, loosend.json and run-loosend.cmd (after editing run-loosend.cmd):
# powershell -ExecutionPolicy Bypass -File install-task.ps1
# Remove: Unregister-ScheduledTask -TaskName loosend -Confirm:$false
# Why not `sc.exe create`? loosend is a plain console program, not a Windows service (it does not speak the service control
# protocol), so the service manager would stop it after 30 seconds. A scheduled task needs nothing extra. If you prefer a real
# service, wrap the same command with a service wrapper such as NSSM (https://nssm.cc/, a third-party tool we do not ship).
$dir = Split-Path -Parent $MyInvocation.MyCommand.Path
New-Item -ItemType Directory -Force -Path "C:\ProgramData\loosend" | Out-Null
$action = New-ScheduledTaskAction -Execute "$dir\run-loosend.cmd" -WorkingDirectory $dir
$trigger = New-ScheduledTaskTrigger -AtStartup
$settings = New-ScheduledTaskSettingsSet -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit ([TimeSpan]::Zero) -StartWhenAvailable
Register-ScheduledTask -TaskName loosend -Action $action -Trigger $trigger -Settings $settings -User "SYSTEM" -RunLevel Highest -Force | Out-Null
Start-ScheduledTask -TaskName loosend
Write-Host "loosend registered and started. Logs: C:\ProgramData\loosend\loosend.log Check: curl.exe http://127.0.0.1:8080/health"
Kubernetes, Helm charts or a managed setup: ask us.
Docker (optional)
The image is public on GitHub's container registry, ghcr.io/sicena-com/loosend (tagged with the version number, which the command below pins, and latest; pin the version in production). No login is needed to pull it. It serves on port 8080, keeps its snapshots in the volume mounted on /data (so the catalogues survive replacing the container), and takes its settings from the LOOSEND_* environment variables (admin key, licence, allowed origins; see the table below), or --env-file loosend.env with the example file above:
docker run -d --name loosend --restart unless-stopped -p 127.0.0.1:8080:8080 -v loosend-data:/data \
-e LOOSEND_ADMIN_KEY="$(openssl rand -hex 24)" \
-e LOOSEND_ALLOWED_ORIGINS=https://www.example.com \
-e LOOSEND_LICENCE='LSN1....' \
ghcr.io/sicena-com/loosend:1.0.0
The container runs as a non-root user on a distroless base (no shell). The image is the same program as the binary downloads; use whichever you prefer.
Define a catalogue and load items
A catalogue has a schema: a list of attributes of kind numeric, text or set. The admin calls need your admin key; the explain call is public (that is what the widget uses).
H=http://localhost:8080
K=your-admin-key
# Define a catalog: each attribute is numeric, text (one string) or set (several strings)
curl -X PUT $H/v1/catalogs/apartments -H "Authorization: Bearer $K" \
-d '{"attributes":[{"name":"rent","kind":"numeric"},{"name":"town","kind":"text"},{"name":"features","kind":"set"}]}'
# Load items (an existing id is replaced)
curl -X POST $H/v1/catalogs/apartments/items -H "Authorization: Bearer $K" \
-d '[{"id":"a1","values":{"rent":1450,"town":"Lausanne","features":["balcony","view"]}}]'
# Ask (this call is public, like the widget's)
curl -X POST $H/v1/catalogs/apartments/explain \
-d '{"constraints":[{"attr":"town","op":"eq","value":"Lausanne"},{"attr":"rent","op":"le","value":1000}]}'
Item ids are your own strings. A bulk upsert (POST on /items) replaces items with the same id; PUT on /items replaces the whole catalogue (the new one is built off-line and swapped in, so searches are not blocked). null or a missing attribute means “unknown” and violates every constraint. A bad item rejects the whole batch.
Load from a feed
A catalogue defined in the configuration file can declare a feed: the server fetches a file or URL every few minutes. There are no database drivers: export your product query to CSV or JSON (a cron job, a view served over HTTP), or push with the API.
{
"addr": ":8080",
"allowedOrigins": ["https://www.example.com"],
"dataDir": "/var/lib/loosend",
"catalogs": {
"apartments": {
"readKey": "replace-with-a-random-string",
"schema": {"attributes": [
{"name": "rent", "kind": "numeric"},
{"name": "town", "kind": "text"},
{"name": "features", "kind": "set"}
]},
"feed": {"source": "https://www.example.com/export/apartments.csv", "format": "csv",
"intervalSeconds": 300, "mode": "replace", "idColumn": "sku"}
}
}
}
format:csv(header row required; one column per attribute plus the id column; extra columns ignored; empty cell = unknown; sets separated bysetSeparator, default|),json(an array of flat objects) orndjson(one flat object per line).mode:replace(default: the catalogue becomes exactly the feed) orupsert(items missing from the feed are kept).- A feed is applied all or nothing: a bad row, an exceeded item limit or a network error leaves the previous data in place and is reported by
/health(feed.lastError). - A catalogue loaded by a feed refuses item writes (
409 managed_by_feed); one defined in the file cannot be redefined or deleted through the API. headers(for authenticated feed URLs) live in the config file: protect its permissions or inject it as a secret.
Use it from the widget
const widget = Loosen.mount(document.getElementById("loosen"), {
licence: "YOUR_LICENCE_KEY",
server: {endpoint: "https://loosend.example.com", catalog: "apartments", key: "YOUR_READ_KEY"}, // key: only if the catalogue has a read key
attributes: { // in server mode only labels and formats; the server knows the kinds
rent: {label: "Rent", format: v => v + " CHF"},
town: {label: "Town"},
},
getConstraints, // as in the install guide
applyRelaxation,
});
widget.update();
allowedOrigins (LOOSEND_ALLOWED_ORIGINS) is the CORS allow-list: it must contain the origin of the page that hosts the widget (no trailing slash). With originsFromLicence the origins whose host your licence covers are allowed too. If your licence lists domains, a browser request from another domain is refused (403 origin_not_licensed) even if it is in the allow-list.
Read key. A catalogue may have a readKey (8 to 128 printable characters): then explain needs it in the X-Loosen-Key header, which the widget sends from its server.key option. Set it in the config file (as above), or with PUT /v1/catalogs/{name}/read-key for catalogues made through the API (DELETE removes it; only a SHA-256 of the key is kept, and it is compared in constant time). The key is visible in your page's source, so it is not a secret: it lets you revoke and limit access per catalogue, not hide data from somebody who reads the page. To rotate it, set the new key and deploy the page with the new server.key; the old key stops working at once.
Configuration
A JSON file (--config; unknown fields are an error) with environment overrides. The flag --addr wins over both.
| Config key | Environment | Default | Meaning |
|---|---|---|---|
addr | LOOSEND_ADDR | :8080 | listen address |
adminKey | LOOSEND_ADMIN_KEY | required, 16+ characters | key of the admin endpoints |
licence | LOOSEND_LICENCE | none | your licence key; without a valid one the server runs in evaluation mode (1,000 items) |
licencePublicKey | LOOSEND_LICENCE_PUBLIC_KEY | built in | ignored (a warning is logged): the server only accepts licences signed by the Loosen production key, which is built in |
dataDir | LOOSEND_DATA_DIR | none (no persistence) | snapshot directory (/data in the image) |
snapshotSeconds | 60 | snapshot period (changed catalogues only) | |
allowedOrigins | LOOSEND_ALLOWED_ORIGINS (comma list) | none | CORS allow-list for explain, https://host[:port] |
originsFromLicence | false | also allow the origins whose host the licence covers | |
trustProxy | LOOSEND_TRUST_PROXY | false | client IP = last X-Forwarded-For entry (set it behind a reverse proxy) |
rateLimitPerSecond, rateLimitBurst | LOOSEND_RATE_PER_SECOND, LOOSEND_RATE_BURST | 20, 40 | per-IP token bucket on explain (negative rate disables) |
maxExplainBodyBytes | 65536 | explain body limit | |
maxAdminBodyBytes | 512 MiB | admin body limit | |
maxConstraints | 24 | per explain request; at most 64 | |
maxExplainWork | 0 (20,000,000 steps) | work budget of the exponential search per explain; beyond it the answer is 422 too_complex | |
maxExplainSize, defaultMinItemsSize | 6, 4 | largest maxSize accepted; maxSize applied when minItems > 1 and none is given | |
maxConcurrentExplains | 4 x CPUs | explanations in flight; others wait up to 5 s, then 503 | |
readTimeoutSeconds, writeTimeoutSeconds | 120, 60 | HTTP timeouts (the header timeout is 10 s) | |
catalogs | none | catalogues defined by the file: {name: {schema, feed, readKey}} |
Licence behaviour
- A valid licence of plan
businessortrialsets the item limit (all catalogues together) to itsmaxItems. Astarterlicence is browser-only: the server reports it as invalid and stays in evaluation mode. - A licence that is bad (signature, key, plan) or expired does not stop the process: it runs in evaluation mode (1,000 items) and
/healthsays why. - The public key that checks licences is built into the server. A
licencePublicKey/LOOSEND_LICENCE_PUBLIC_KEYsetting is ignored (a warning is logged). - If the licence lists domains, explain requests from a browser whose
Originis on another domain get403 origin_not_licensed(the admin key is exempt). - Writes beyond the limit are refused (
403 item_limit, nothing applied). If the instance already holds more than the limit (the licence expired while running), explain answers403 licence_requireduntil you reduce the catalogues or install a new licence. - When your subscription renews we email you a new key. Replace
LOOSEND_LICENCEand restart the server: it keeps its snapshots.
The API
JSON in, JSON out. Errors always look like {"error": "bad_constraint", "message": "..."} with a stable code.
| Endpoint | Who | What |
|---|---|---|
GET /health | public | status, version, items, licence state, feed state per catalogue |
POST /v1/catalogs/{name}/explain | public (CORS, licence domains, optional read key, rate limit, work budget) | the explanation of a set of constraints |
PUT /v1/catalogs/{name} | admin | define a catalogue (a different schema empties it) |
GET /v1/catalogs, GET / DELETE /v1/catalogs/{name} | admin | list, show, delete |
POST / PUT /v1/catalogs/{name}/items | admin | bulk upsert / replace all |
DELETE /v1/catalogs/{name}/items/{id} | admin | delete one item |
PUT / DELETE /v1/catalogs/{name}/read-key | admin | set (rotate) or remove the catalogue's read key |
Admin calls send Authorization: Bearer <key> (or X-Admin-Key); they never send CORS headers. The explain body is {"constraints": [...], "minItems": 1, "maxSize": 0, "order": "cost"} with the same constraints as the widget. order is "cost" (the default: cheapest change first) or "canonical" (by number of constraints, then by constraint index); anything else is 400 bad_options. The answer lists relaxations and conflicts, plus items, matching, success and tookMs. Constraint indexes refer to the position in your request.
- Each relaxation is a minimal set of changes that makes the query succeed, to apply together:
{"changes": [{"constraint": 1, "action": "adapt", "value": 20000, "cost": 0.1667}], "results": 1, "cost": 0.1667}.resultsis how many items match the whole query once the changes are applied (never fewer thanminItems);costis the sum of the cost of its changes. The list is sorted before it is cut, so a client that shows the first N shows the cheapest N. - The cost of a change is
1for aclear; for anadaptit is the distance between the new and the old bound divided by the range of the attribute in the catalogue (largest minus smallest value), at most1. - Each conflict is a minimal set of constraints that cannot be satisfied together:
{"constraints": [0, 1], "local": [...]}, wherelocallists the changes that solve that conflict alone, cheapest first, each with itscostbut no result count (it answers a sub-question about only those constraints). The conflicts themselves stay in canonical order.
Security
- The admin key is the only secret to protect. Keep the admin endpoints off the public internet (a reverse-proxy rule or a network policy). Wrong keys are compared in constant time and throttled per IP.
- explain is public by design, because the page's JavaScript is public. The CORS allow-list and the licence domains stop other websites' browsers; an optional read key lets you revoke and limit access per catalogue; the per-IP rate limit, the concurrency cap, the 64 KiB body limit, the constraint cap (24) and the work budget (
422 too_complex) bound what one request can cost. Be aware of the limits: a program that is not a browser can omit or forge theOriginheader, and the read key is visible in the page. Neither is a secret. - Put TLS in front (a reverse proxy or load balancer) and set
trustProxy. - Catalogue data is not logged; request logs hold method, path, status, duration and client IP. Snapshots are plain files in
dataDir, written atomically and readable by the process user only.
Performance
Measured on a 10-core development machine with 20 concurrent clients, a catalogue of 7 attributes and queries of 6 constraints:
| Items | Requests per second | p50 | p95 | p99 |
|---|---|---|---|---|
| 100,000 | about 1,900 | 8 ms | 23 ms | 37 ms |
| 1,000,000 | about 185 | 96 ms | 205 ms | 275 ms |
The cost of a request is linear in items times constraints: a catalogue of 10,000 items answers in about 1 ms. Loading 1 million items takes about 2 seconds and about 170 MiB of memory. Your numbers depend on your hardware.