A data generating app is written as a YAML simulation that desflow runs, and it ingests the theLook eCommerce data continuously into a PostgreSQL database. A WebSocket server, built by FastAPI, periodically queries the data to serve its clients. In this series, we develop real-time monitoring dashboard applications, and this post walks through the data generation app and backend API. The monitoring dashboards will be developed using Streamlit and Next.js, with Apache ECharts for visualization. They will be discussed in later posts.
[Update 2026-11-15] The data generator is now one YAML file, model.yaml, which desflow 1.0.0 runs with desflow run model.yaml. It replaces the Python modules in sales/simulation, apart from the control command, and it creates the tables itself. The code, commands and log below show the new version.
[Update 2026-10-16] dynamic-des is now desflow: pip install desflow, import desflow and the desflow command. The parameter table’s columns are path and value, which the PostgreSQL ingress reads from desflow 0.21.0.
Services

We have three services, and they are illustrated separately below. The source of this post can be found in the live-dashboard folder of the benchtop GitHub repository. It is one of the Benchtop projects, which run locally from a fresh clone. The development environment can be constructed as follows:
1$ git clone https://github.com/jaehyeon-kim/benchtop.git
2$ cd benchtop/live-dashboard
3$ uv venv
4$ source .venv/bin/activate
5(.venv) $ uv pip install -r requirements.txt
PostgreSQL
A PostgreSQL database server is started with odctl, which runs it with Docker Compose on port 5432.
1(.venv) $ odctl up postgres
The data generator creates a dedicated schema named dashboard and its tables when it starts. Each table’s columns and primary key are set in the data generator’s model file, shown below.
Data Generator
The data generator is a desflow simulation of the shop. The simulation is one YAML file, model.yaml, and the desflow command runs it in its own terminal. The file sets the PostgreSQL address and every setting of the simulation. It runs until it is stopped (--until '10 min' stops it after ten minutes).
1(.venv) $ desflow run model.yaml
Data Generator Source
The theLook eCommerce dataset is reduced to four entities, three of which are dynamically generated. Visitors arrive at random, view a few pages, and some buy. A buyer is a new or a returning user, and each purchase creates an order with one or more order items. Each order waits for a warehouse picker, then ships and completes, or is cancelled when no picker comes in time. Every change of status updates the order and its items. In the file, each step is a task, and a task’s payload is the row it writes, with __table__ naming the table. The egress section writes each row to its table, and the ingress section applies parameter changes while the simulation runs.
1# live-dashboard/model.yaml
2# The shop, run in real time into PostgreSQL. Visitors arrive and browse, and some buy.
3# Each order waits for a picker, ships and completes, or is cancelled when no picker
4# comes in time. Every rate, time and chance is a registry parameter, so a row added to
5# dashboard.params (sales.simulation.control) changes it while the model runs.
6simulation:
7 sim_id: sales
8 factor: 1
9 logical_start_time: now
10 timezone: UTC
11
12# The ingress applies the rows of its parameter table that are not applied yet, every
13# two seconds
14ingress:
15 - type: Postgres
16 config:
17 connection_dsn: "${PG_DSN:-postgresql://user:password@127.0.0.1:5432/odctl}"
18 table_name: dashboard.params
19
20# A few rows arrive a second
21batching: {batch_size: 4, flush_interval: 1.0}
22
23# One entry per table: an entry writes the events whose __table__ names its table and
24# ignores the others. `envelope: false` writes the payload alone, so no task record
25# reaches a table, and `when` drops the record of an order that leaves the picking
26# queue, which the `cancelled` task writes as a row instead. `tables` makes the `dashboard` schema and the table at start when
27# they do not exist. Orders and their items upsert on id, because their status changes.
28egress:
29 - type: Postgres
30 when: &rows {expr: "record.stream_type == 'event' and record.value.status != 'reneged'"}
31 envelope: false
32 config:
33 connection_dsn: "${PG_DSN:-postgresql://user:password@127.0.0.1:5432/odctl}"
34 table_name: users
35 server_settings: {search_path: dashboard}
36 tables:
37 dashboard.users:
38 columns:
39 id: TEXT
40 age: INT
41 gender: TEXT
42 country: TEXT
43 traffic_source: TEXT
44 created_at: TEXT
45 primary_key: id
46 - type: Postgres
47 when: *rows
48 envelope: false
49 config:
50 connection_dsn: "${PG_DSN:-postgresql://user:password@127.0.0.1:5432/odctl}"
51 table_name: orders
52 server_settings: {search_path: dashboard}
53 upsert_keys: [id]
54 tables:
55 dashboard.orders:
56 columns:
57 id: TEXT
58 user_id: TEXT
59 status: TEXT
60 num_of_item: INT
61 created_at: TEXT
62 primary_key: id
63 - type: Postgres
64 when: *rows
65 envelope: false
66 config:
67 connection_dsn: "${PG_DSN:-postgresql://user:password@127.0.0.1:5432/odctl}"
68 table_name: order_items
69 server_settings: {search_path: dashboard}
70 upsert_keys: [id]
71 tables:
72 dashboard.order_items:
73 columns:
74 id: TEXT
75 order_id: TEXT
76 user_id: TEXT
77 product_id: BIGINT
78 status: TEXT
79 sale_price: FLOAT8
80 created_at: TEXT
81 primary_key: id
82 - type: Postgres
83 when: *rows
84 envelope: false
85 config:
86 connection_dsn: "${PG_DSN:-postgresql://user:password@127.0.0.1:5432/odctl}"
87 table_name: products
88 server_settings: {search_path: dashboard}
89 tables:
90 dashboard.products:
91 columns:
92 id: BIGINT
93 name: TEXT
94 category: TEXT
95 department: TEXT
96 retail_price: FLOAT8
97 cost: FLOAT8
98 primary_key: id
99
100# Chances that a visitor is a registered user, buys, and returns a delivered order;
101# `users` counts the users made so far
102variables: {returning: 0.6, buy: 0.3, return: 0.1, users: 0}
103
104# Mean and standard deviation in seconds
105services:
106 page_view: {dist: lognormal, mean: 4.0, std: 2.0}
107 pick: {dist: lognormal, mean: 5.0, std: 2.0}
108 transit: {dist: lognormal, mean: 60.0, std: 20.0}
109 return_after: {dist: lognormal, mean: 60.0, std: 30.0}
110 patience: {dist: lognormal, mean: 120.0, std: 60.0}
111
112# Warehouse pickers packing orders at once
113resources:
114 pickers: {current_cap: 10, max_cap: 20}
115
116arrivals:
117 # The 260 products of products.csv, written in id order when the run starts
118 catalogue: {initial: 260, spawn: product_row}
119 # Visitors a second, exponential gaps
120 visitor:
121 dist: exponential
122 rate: 4
123 spawn: catalogue_check
124 attributes:
125 n: 0
126 pages: {gen: integer, bounds: [2, 5]}
127
128tasks:
129 product_row:
130 vars:
131 p: {gen: row, file: products.csv, order: sequential}
132 payload:
133 __table__: products
134 id: {gen: var, name: p, path: id}
135 name: {gen: var, name: p, path: name}
136 category: {gen: var, name: p, path: category}
137 department: {gen: var, name: p, path: department}
138 retail_price: {gen: var, name: p, path: retail_price}
139 cost: {gen: var, name: p, path: cost}
140 # A visitor is a returning user, chosen at the start of the visit from the users made
141 # so far, with the chance `returning` once a user exists
142 catalogue_check:
143 payload: null
144 next:
145 weights:
146 pick_user: "registry['sales.variables.returning'] if
147 registry['sales.variables.users'] > 0 else 0"
148 no_user: "1 - (registry['sales.variables.returning'] if
149 registry['sales.variables.users'] > 0 else 0)"
150 # An earlier user, each with the same chance; no visitor is sent here before a user
151 # exists
152 pick_user:
153 payload: null
154 set:
155 user: {gen: lookup, task: new_user, path: id}
156 next: pages
157 no_user:
158 payload: null
159 set: {user: ""}
160 next: pages
161 # Two to five page views, a loop of `next`
162 pages:
163 service_time: {gen: sample, service: page_view}
164 payload: null
165 set:
166 n: {gen: expr, expr: "attr.n + 1"}
167 next:
168 when:
169 - {condition: "attr.n < attr.pages", task: pages}
170 default: buy_choice
171 # The chance to buy is a live variable, read for each visitor
172 buy_choice:
173 payload: null
174 next:
175 weights:
176 buyer: "registry['sales.variables.buy']"
177 walk_away: "1 - registry['sales.variables.buy']"
178 walk_away:
179 payload: null
180 # A returning visitor orders for the user chosen at the start; a new user is made only
181 # here
182 buyer:
183 payload: null
184 next:
185 when:
186 - {condition: "attr.user != ''", task: returning}
187 default: new_user
188 returning:
189 payload: null
190 next: order
191 new_user:
192 on:
193 - path: sales.variables.users
194 value: {gen: expr, expr: "registry['sales.variables.users'] + 1"}
195 vars:
196 uid: {gen: uuid}
197 # the order names its user in orders.user_id
198 set:
199 user: {gen: var, name: uid}
200 payload:
201 __table__: users
202 id: {gen: var, name: uid}
203 age: {gen: integer, bounds: [12, 70]}
204 gender: {gen: one_of, choices: [F, M]}
205 country:
206 gen: weighted
207 options:
208 China: 7319934
209 Brasil: 7294477
210 South Korea: 1493470
211 France: 1458801
212 United States: 1157308
213 United Kingdom: 1024009
214 traffic_source:
215 gen: weighted
216 options:
217 Search: 0.7
218 Organic: 0.15
219 Facebook: 0.06
220 Email: 0.05
221 Display: 0.04
222 created_at: {gen: now}
223 next: order
224 # One to four items (70%, 20%, 5% and 5%), each a different product
225 order:
226 vars:
227 # the order's row and every later row of it carry this id
228 oid: {gen: uuid}
229 created: {gen: now}
230 n:
231 gen: expr
232 expr: "1 if u < 0.7 else 2 if u < 0.9 else 3 if u < 0.95 else 4"
233 names:
234 u: {gen: uniform, low: 0, high: 1}
235 ids:
236 gen: repeat
237 times: {gen: var, name: n}
238 value: {gen: uuid}
239 set:
240 order_id: {gen: var, name: oid}
241 created_at: {gen: var, name: created}
242 n: {gen: var, name: n}
243 iids: {gen: var, name: ids}
244 products:
245 gen: repeat
246 times: {gen: var, name: n}
247 value: {gen: lookup, task: product_row, distinct: true}
248 payload:
249 __table__: orders
250 id: {gen: var, name: oid}
251 user_id: {gen: attr, name: user}
252 status: Processing
253 num_of_item: {gen: var, name: n}
254 created_at: {gen: var, name: created}
255 next: items
256 items:
257 wait:
258 each: "range(attr.n)"
259 branch:
260 task: order_item
261 args:
262 i: {gen: expr, expr: each.value}
263 status: Processing
264 payload: null
265 next: pick
266 # one item row; a status change writes every item again with the same id
267 order_item:
268 vars:
269 p: {gen: expr, expr: "attr.products[arg.i]"}
270 payload:
271 __table__: order_items
272 id: {gen: expr, expr: "attr.iids[arg.i]"}
273 order_id: {gen: attr, name: order_id}
274 user_id: {gen: attr, name: user}
275 product_id: {gen: var, name: p, path: id}
276 status: {gen: expr, expr: arg.status}
277 sale_price: {gen: var, name: p, path: retail_price}
278 created_at: {gen: attr, name: created_at}
279 # An order that waits longer than its patience for a picker is cancelled
280 pick:
281 resource: pickers
282 service: pick
283 patience: {gen: sample, service: patience}
284 on_renege: cancelled
285 payload:
286 __table__: orders
287 id: {gen: attr, name: order_id}
288 user_id: {gen: attr, name: user}
289 status: Shipped
290 num_of_item: {gen: attr, name: n}
291 created_at: {gen: attr, name: created_at}
292 next: items_shipped
293 items_shipped:
294 wait:
295 each: "range(attr.n)"
296 branch:
297 task: order_item
298 args:
299 i: {gen: expr, expr: each.value}
300 status: Shipped
301 payload: null
302 next: transit
303 cancelled:
304 payload:
305 __table__: orders
306 id: {gen: attr, name: order_id}
307 user_id: {gen: attr, name: user}
308 status: Cancelled
309 num_of_item: {gen: attr, name: n}
310 created_at: {gen: attr, name: created_at}
311 next: items_cancelled
312 items_cancelled:
313 wait:
314 each: "range(attr.n)"
315 branch:
316 task: order_item
317 args:
318 i: {gen: expr, expr: each.value}
319 status: Cancelled
320 payload: null
321 transit:
322 service: transit
323 payload:
324 __table__: orders
325 id: {gen: attr, name: order_id}
326 user_id: {gen: attr, name: user}
327 status: Complete
328 num_of_item: {gen: attr, name: n}
329 created_at: {gen: attr, name: created_at}
330 next: items_complete
331 items_complete:
332 vars:
333 sent_back:
334 gen: boolean
335 p: {gen: param, path: sales.variables.return}
336 wait:
337 each: "range(attr.n)"
338 branch:
339 task: order_item
340 args:
341 i: {gen: expr, expr: each.value}
342 status: Complete
343 payload: null
344 next:
345 when:
346 - {condition: "sent_back", task: returned}
347 returned:
348 service: return_after
349 payload:
350 __table__: orders
351 id: {gen: attr, name: order_id}
352 user_id: {gen: attr, name: user}
353 status: Returned
354 num_of_item: {gen: attr, name: n}
355 created_at: {gen: attr, name: created_at}
356 next: items_returned
357 items_returned:
358 wait:
359 each: "range(attr.n)"
360 branch:
361 task: order_item
362 args:
363 i: {gen: expr, expr: each.value}
364 status: Returned
365 payload: null
366
367# `desflow test model.yaml` runs each test unpaced, with no ingress and no egress, and
368# compares its statistics with these. `desflow test model.yaml --fix` writes new values
369# after a deliberate change or a desflow upgrade.
370tests:
371 # One hour at the defaults: the whole catalogue is written, about 1.2 orders arrive a
372 # second, and about four buyers in ten are new users
373 - name: an hour at the defaults
374 seed: 1
375 until: 3600
376 expect:
377 tasks.product_row.finished: 260
378 tasks.new_user.finished: 1795
379 tasks.order.finished: 4375
380 tasks.pick.finished: 4368
381 tasks.transit.finished: 4307
382 tasks.returned.finished: 441
In the following example, the simulation logs the seed it drew, starts and connects to each table.
1(.venv) $ desflow run model.yaml
214:36:44 [INFO] desflow.builder.context: Building SimulationContext for 'sales'...
314:36:44 [INFO] desflow.builder.context: No random_seed was given, so this run uses 1842063416. Repeat it with: desflow run model.yaml --seed 1842063416
414:36:44 [INFO] desflow.core.environment: PostgresEgress has envelope: false, so it skips telemetry and the queued and started records, and writes each event's value alone.
514:36:44 [INFO] desflow.core.environment: PostgresEgress has envelope: false, so it skips telemetry and the queued and started records, and writes each event's value alone.
614:36:44 [INFO] desflow.core.environment: PostgresEgress has envelope: false, so it skips telemetry and the queued and started records, and writes each event's value alone.
714:36:44 [INFO] desflow.core.environment: PostgresEgress has envelope: false, so it skips telemetry and the queued and started records, and writes each event's value alone.
814:36:44 [INFO] desflow.builder.context: Simulation engine started.
914:36:44 [INFO] desflow.connectors.egress.postgres: PostgresEgress connected to users
1014:36:44 [INFO] desflow.connectors.egress.postgres: PostgresEgress connected to order_items
1114:36:44 [INFO] desflow.connectors.egress.postgres: PostgresEgress connected to orders
1214:36:44 [INFO] desflow.connectors.egress.postgres: PostgresEgress connected to products
When the data gets ingested into the database, we see the following tables are created in the dashboard schema.
| Table | One row per |
|---|---|
products | product: 260, from 26 categories, 2 departments and 5 brands |
users | customer, with age, gender, country and traffic source |
orders | order, with its status and number of items |
order_items | product in an order, with its status and sale price |
WebSocket Server
This WebSocket server runs a FastAPI-based API using uvicorn, in its own terminal, on port 8000. It connects to the PostgreSQL database with the settings in sales/core/config.py. The service processes data with a 5-minute lookback window and refreshes every 5 seconds.
1(.venv) $ uvicorn sales.api.server:app --host 127.0.0.1 --port 8000
WebSocket Server Source
This FastAPI WebSocket server streams real-time data from a PostgreSQL database. It connects using asyncpg, fetches order-related data with a configurable lookback window, and sends updates every few seconds as defined by refresh seconds. Each update is a JSON list of records. The app continuously queries the database, sending fresh data to the connected client until it disconnects. Logging ensures visibility into connections and queries.
1# live-dashboard/sales/api/server.py
2"""Sends the recent order items to the dashboards over a WebSocket.
3
4Every `REFRESH_SECONDS`, `/ws` sends the order items of the last `LOOKBACK_MINUTES`,
5with their users and products, as a JSON list of records.
6
7Run: uvicorn sales.api.server:app --host 127.0.0.1 --port 8000
8"""
9
10import asyncio
11import logging
12
13import asyncpg
14from fastapi import FastAPI, WebSocket, WebSocketDisconnect
15
16from sales.core.config import DSN, LOOKBACK_MINUTES, REFRESH_SECONDS
17from sales.stores import postgres
18
19logger = logging.getLogger("uvicorn.error")
20app = FastAPI()
21
22
23@app.websocket("/ws")
24async def stream(websocket: WebSocket) -> None:
25 """
26 Sends the recent order items every `REFRESH_SECONDS`, until the client leaves.
27
28 Args:
29 websocket (WebSocket): The client.
30 """
31 await websocket.accept()
32 conn = await asyncpg.connect(DSN)
33 try:
34 while True:
35 records = await postgres.recent_items(conn, LOOKBACK_MINUTES)
36 logger.info("Sending %d records", len(records))
37 await websocket.send_json(records)
38 await asyncio.sleep(REFRESH_SECONDS)
39 except WebSocketDisconnect:
40 logger.info("Client disconnected")
41 finally:
42 await conn.close()
The query and the function that runs it are in the store module.
1# live-dashboard/sales/stores/postgres.py
2# The order items of the last $1 minutes, with their users and products.
3# clock_timestamp() is the time now; current_timestamp would stay at the transaction's start.
4RECENT_ITEMS = f"""
5SELECT u.id AS user_id, u.age, u.gender, u.country, u.traffic_source,
6 o.order_id, o.id AS item_id, p.category, p.cost, o.status AS item_status,
7 o.sale_price, o.created_at
8FROM {SCHEMA}.order_items AS o
9JOIN {SCHEMA}.users AS u ON u.id = o.user_id
10JOIN {SCHEMA}.products AS p ON p.id = o.product_id
11WHERE o.created_at::timestamptz >= clock_timestamp() - make_interval(mins => $1)
12"""
1# live-dashboard/sales/stores/postgres.py
2async def recent_items(conn: asyncpg.Connection, minutes: int) -> list[dict]:
3 """
4 Reads the order items of the last `minutes`, with their users and products.
5
6 Args:
7 conn (asyncpg.Connection): An open connection.
8 minutes (int): The lookback window.
9
10 Returns:
11 list[dict]: One record per order item.
12 """
13 return [dict(row) for row in await conn.fetch(RECENT_ITEMS, minutes)]
Deploy Services
The services are started with the commands above: PostgreSQL first, then the data generator and the WebSocket server, each in its own terminal. Once started, the server can be checked with the WebSocket client of the websockets package, which is installed with uvicorn, by executing python -m websockets ws://127.0.0.1:8000/ws, and its logs are printed in its terminal.
The client prints each message the server sends: a list of the order items of the last five minutes, here 39 records in the first message.
1python -m websockets ws://127.0.0.1:8000/ws
1Connected to ws://127.0.0.1:8000/ws.
2< [{"user_id":"427f5544-f594-4127-826e-912dc0dd970e","age":40,"gender":"M","country":"China","traffic_source":"Search","order_id":"e8c140bd-087a-4dfe-ac01-29f40a36a27e","item_id":"40deff28-0310-49ed-b11b-fdf0a3dabb24","category":"Active","cost":24.7,"item_status":"Shipped","sale_price":55.04,"created_at":"2026-09-30T13:57:06.948553+00:00"}, ...]
The server logs how many records it sends every five seconds:
1INFO: Started server process [...]
2INFO: Waiting for application startup.
3INFO: Application startup complete.
4INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
5INFO: 127.0.0.1:54478 - "WebSocket /ws" [accepted]
6INFO: connection open
7INFO: Sending 39 records
8INFO: Sending 54 records
9INFO: Sending 67 records
Related posts
- Guide to Building Integrated Web Applications with FastAPI and NiceGUI - serves a FastAPI backend and the web UI from one Python process, compared with React and with Streamlit

Comments