monoblok docs
Docs menu · Start here

Examples

Examples

Every example here is a real file in the repository, shown in full and checked with monoblok --validate. The level labels indicate the amount of configuration and number of forms involved.

How to run them#

Each example in examples/ has a matching .sh script that starts a temporary monoblok, subscribes, publishes sample data and prints what arrived. The scripts need the NATS CLI.

shell
examples/sensors.sh

To run a patchbay yourself, pass the file to monoblok and use any NATS client:

shell
monoblok examples/sensors.edn
nats sub 'sensors.>'
nats pub sensors.temp 42.04

To see what a file does with no server at all, pipe SUBJECT|payload rows through --soundcheck. The site build uses this command to generate the transcripts on these pages:

shell
printf 'sensors.temp|42.01\nsensors.temp|42.04\n' | monoblok --soundcheck --soundcheck-label examples/sensors.edn

When testing with nats pub, pass negative bodies after --, for example nats pub sensors.temp -- -5.

The examples by level#

examplelevelwhat it shows
sensors.ednStarterround + squelch on a noisy sensor
lvc.ednStarter$LVC.> replay: a late joiner gets the last value
demo.ednStarterone rule for each primitive family
office-temp.ednIntermediatemoving-average alert and all-clear with transition and hysteresis
rental-car.ednIntermediatequantize, deadband and an over-rev alert, in EDN and YAML
json-frames.ednIntermediatejson-demux! a JSON device into scalar sub-subjects
ask.ednIntermediatejoin two subjects with last, answer a request with reply!
clocked.ednAdvancedsilence detection, debounce, sampling, clocked aggregates, every, a funnel
latency-stats.ednIntermediatelive p50/p95/p99/stddev over a sliding window
ticker.ednIntermediateround, squelch, big-jump alerts, export
bars.ednIntermediatetick-count OHLC bars per symbol, alerting on closed bars
json-massive/Advanceda multi-asset JSON feed demuxed, cleaned and alerted on
bar-cardinality.ednAdvancedmeasuring memory for bars across a large symbol universe
bridge.ednIntermediateexport selected subjects to a real NATS server
import.ednIntermediatetap remote subjects, keep raw input private, export the clean stream
jetstream.ymlAdvancedreplay a populated JetStream stream, then continue live
waf.ednIntermediatea WAF for NATS: regex payload scan, p99 outlier gate, flood detection
deidentify.ednIntermediatestrip identifiers from patient frames: allow-list fields, age bands, ward aggregates, masked notes
cold-store.ednIntermediatefreezer monitoring written by a coding agent: demux, dedupe, hysteresis alert, door count
moonwell_patchbay.ednAdvanced24 rules over nested JSON telemetry, using most of the language
cloudhook_patchbay.ednAdvanced23 rules: a second large generated patchbay

Round and squelch#

Starter The canonical first rule. A jittery sensor publishes readings that differ in the second decimal place; subscribers only care when the value really moves.

examples/sensors.edn
(on "sensors.*"
  (-> payload-float
      (round 1)
      (squelch)
      (publish! (subject-append "stable"))))

payload-float parses the payload as a number, round trims it to one decimal place, squelch passes it only if it differs from the last value seen on this subject, and publish! sends it to <subject>.stable. When squelch suppresses, it returns nil, and publish! on nil does nothing.

soundcheck · examples/sensors.edn
in   sensors.temp  42.01
out  sensors.temp.stable  42
in   sensors.temp  42.04
in   sensors.temp  42.08
out  sensors.temp.stable  42.1
in   sensors.temp  42.12
in   sensors.temp  43.00
out  sensors.temp.stable  43
in   sensors.temp  43.00
in   sensors.temp  43.01

Seven readings in, three out. State is per subject, so sensors.temp and sensors.humidity are deduplicated independently by the same rule.

Last-value cache#

Starter A normal subscriber sees nothing until the next publish. The last-value cache fixes that: opt subjects in with (lvc ...), and a subscriber to $LVC.<subject> gets the cached value immediately, then live updates.

examples/lvc.edn
;; LVC example: opt all subjects into $LVC.<subject> last-value streams.
(lvc [">"])
(on "never.matches" (publish! "never" payload))
shell
# Publish a value before subscribing.
nats pub sensors.temp 23.5

# Later, subscribe. A normal SUB would see nothing until the next publish.
nats sub '$LVC.sensors.temp'
# -> prints "23.5" immediately

Single-quote any subject starting with $ so your shell does not try to expand it. The cache pairs particularly well with conditioning rules: a subscriber to $LVC.sensors.temp.stable gets the most recent rule-produced value on connect, not the raw input. More in LVC, stats and snapshots.

A tour of the primitives#

Starter This is the patchbay loaded on the public demo server. It includes examples from each form family: squelch for value dedup, deadband for "ignore small wobbles", moving-avg for smoothing, delta for per-tick change, transition for boolean edge detection, rising-edge for one-shot crossings, hold-off for time-based rate limiting, and count! for tallies.

examples/demo.edn
;; Public demo patchbay for demo.monoblok.host:4222.
;;
;; Everything is scoped under `demo.>` so visitors can't stomp on server
;; internals or each other's namespaces. Each rule below is an example
;; of one patchbay primitive; see docs/demo.md for the companion walkthrough.

(lvc ["demo.>"])

;; 1. Squelch: round to 1dp, only emit when the rounded value changes.
;;    Publish to `demo.sensors.temp` and watch `demo.sensors.temp.stable`.
(on "demo.sensors.*"
  (-> payload-float
      (round 1)
      (squelch)
      (publish! (subject-append "stable"))))

;; 2. Deadband: analog-style suppression; ignore moves smaller than 0.5.
;;    Publish to `demo.sensors.temp` and watch `demo.sensors.temp.delta`.
(on "demo.sensors.*"
  (-> payload-float
      (deadband 0.5)
      (publish! (subject-append "delta"))))

;; 3. Moving average + deadband: smooth a noisy stream over 10 samples
;;    and only emit when the smoothed value drifts by at least 1.0.
;;    Watch `demo.sensors.*.smoothed`.
(on "demo.sensors.*"
  (-> payload-float
      (moving-avg 10)
      (deadband 1.0)
      (publish! (subject-append "smoothed"))))

;; 3b. Time-windowed average: 5-second sliding mean. Old samples expire
;;     by age, so the average self-drains when the publisher goes quiet.
;;     Watch `demo.sensors.*.avg5s`.
(on "demo.sensors.*"
  (-> payload-float
      (moving-avg :ms 5000)
      (publish! (subject-append "avg5s"))))

;; 4. Delta + squelch: emit the per-tick change, but only when it
;;    differs from the last delta (so a stream of identical values
;;    doesn't produce a stream of zeros). 0 on first sight.
;;    Watch `demo.sensors.*.delta-abs`.
(on "demo.sensors.*"
  (-> (delta payload-float)
      (squelch)
      (publish! (subject-append "delta-abs"))))

;; 5. Transition: one rule covers both edges of a threshold. Fires
;;    "hot" once on crossing > 28, "cool" once on crossing back.
;;    Watch `demo.sensors.*.alert` and `demo.sensors.*.ok`.
(on "demo.sensors.*"
  (transition (> payload-float 28.0)
    (publish! (subject-append "alert") "hot")
    (publish! (subject-append "ok")    "cool")))

;; 6. Hold-off: leading-edge rate gate. While above 40, emit at most
;;    once every 2s. Publish faster than that and extra publishes are
;;    dropped silently. Watch `demo.sensors.*.overload`.
(on "demo.sensors.*"
  (when (> payload-float 40.0)
    (-> payload
        (hold-off 2000)
        (publish! (subject-append "overload")))))

;; 7. Rising-edge: only fire on the false-to-true transition. Useful
;;    when you care about "went high" but not "is high."
;;    Watch `demo.sensors.*.spike`.
(on "demo.sensors.*"
  (-> (rising-edge (> payload-float 50.0))
      (publish! (subject-append "spike"))))

;; 8. Alert mirror: anything on `demo.log.*` whose payload contains
;;    "alert" is copied to `demo.alerts`. Subject-token demo too:
;;    `(subject-token 2)` is the third dot-separated token.
(on "demo.log.*"
  (when (contains? payload "alert")
    (publish! "demo.alerts"
      (str-concat "[" (subject-token 1) "] " payload))))

;; 9. Count: a running tally of threshold crossings, not raw samples.
;;    Increments once per false->true transition above 50, publishes
;;    the new total to `demo.sensors.*.count`. Pair with example 7
;;    (rising-edge "spike") and watch the count climb in lockstep.
(on "demo.sensors.*"
  (count! (rising-edge (> payload-float 50.0))))

(export
   :servers  ["nats://127.0.0.1:4223"]
   :name     "monoblok-prod-1"
   :export   ["demo.sensors.*.spike" "demo.alerts.>"])

Try it against the public server without installing anything:

shell
nats context save monoblok-demo --server nats://demo.monoblok.host:4222
nats context select monoblok-demo

# One terminal
nats sub 'demo.>'

# Another
nats pub demo.sensors.temp 25.3
nats pub demo.sensors.temp 25.34
nats pub demo.sensors.temp 25.38

The first terminal prints a handful of derived subjects: demo.sensors.temp.stable, .delta, .smoothed, .delta-abs. Each one comes from a different patchbay rule applied to the input. The client publishing the raw readings does not know any of those rules exist.

publish herewatch herewhat the rule does
demo.sensors.<name> (a number)demo.sensors.<name>.stableround 1 then squelch (emit when the rounded value moves)
demo.sensors.<name>.deltadeadband 0.5 (suppress moves smaller than 0.5)
demo.sensors.<name>.smoothedmoving-avg 10 then deadband 1.0
demo.sensors.<name>.avg5smoving-avg :ms 5000, a 5-second sliding mean
demo.sensors.<name>.delta-absper-tick numeric delta (0 on first sight)
demo.sensors.<name>.alert / .oktransition across 28.0: "hot" rising, "cool" falling
demo.sensors.<name>.overloadhold-off 2000 while above 40 (one emit per 2s)
demo.sensors.<name>.spikerising-edge across 50.0
demo.sensors.<name>.countcount! of false-to-true crossings above 50.0
demo.log.<name> (any text)demo.alertsmirror if the payload contains alert, prefixed with the source

The same file exists as demo.yml and demo.json if you want to compare the three spellings rule by rule. The demo server is shared and public with no auth, so do not send secrets. The demo walkthrough has more to try, and the live demo page drives the same server from your browser.

MIT licensed · © 2026 Alex Reid
Lexvica offers solutions built with monoblok.