Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 31 ยท Bokeh

Bokeh Server and Streaming Data

Run Bokeh apps with bokeh serve, use curdoc and Python callbacks, stream live data with stream() and patch(), and keep a rolling window with rollover.

A Bokeh chart saved as an HTML file is a snapshot with some JavaScript. That is enough for a slider or a hover tooltip. But some jobs need Python to stay in the loop: a chart that shows live sensor values, a dashboard that re-queries a database when you pick a date, or a calculation that is too heavy (or too secret) to ship to the browser. For these, Bokeh has a server.

The Bokeh server keeps a Python process running, holds a copy of the document for each browser session, and keeps it synchronized with BokehJS over a WebSocket. You write normal Python callbacks; when the data in Python changes, the browser updates. This lesson shows how to run an app, how callbacks work, and how to stream data efficiently with stream(), patch() and rollover.

A Bokeh server is a long-running Python process, so none of it can run on this site. The Bokeh and shell code below is read-only. The runnable examples are stand-ins in plain JavaScript: a source with stream, patch and rollover, and a periodic callback that feeds it. They show what the data operations do and why they are efficient, not how the real WebSocket protocol works.

Your first server app

A Bokeh server app is an ordinary Python script that builds a document and attaches it to curdoc(), the "current document" for the session. Here is a chart that draws a new random-walk point every half second:

Python
# app.py
from random import gauss

from bokeh.layouts import column
from bokeh.models import ColumnDataSource
from bokeh.plotting import curdoc, figure

source = ColumnDataSource(data={"step": [0], "value": [0.0]})

p = figure(height=300, width=700, title="Random walk")
p.line("step", "value", source=source, line_width=2)

state = {"step": 0, "value": 0.0}


def update():
    state["step"] += 1
    state["value"] += gauss(0, 1)
    source.stream({"step": [state["step"]], "value": [state["value"]]}, rollover=100)


curdoc().add_periodic_callback(update, 500)  # every 500 milliseconds
curdoc().add_root(column(p))
curdoc().title = "Live random walk"

Start it from a terminal in the same folder:

Terminal
bokeh serve --show app.py

Bokeh serves the app at http://localhost:5006/app (the URL path is the file name without .py) and --show opens a browser tab. Edit the file, reload the tab, and you see the change; the server runs the script again for every new session.

Two ideas matter here:

  • One document per session. Every browser tab that opens the URL runs your script and gets its own curdoc(), its own source and its own state. Two readers do not interfere. That is why the state dictionary above is safe: it is created per session by the script run.
  • Callbacks run in the server process. add_periodic_callback(update, 500) calls update every 500 ms for this session. When update changes the source, the server sends the change to that session's browser.

Useful command-line options: --port 5007 to pick a port, --allow-websocket-origin=example.com to allow a public host name (required when the server sits behind a proxy or a domain), and bokeh serve app_folder/ for a directory app with a main.py, plus optional templates/ and static/ folders. Several scripts can be served together, each at its own URL.

Python callbacks for widgets

Widgets and Python callbacks work together on the server. A widget's on_change receives the attribute name, the old value and the new value:

Python
from bokeh.models import Select, Slider

window = Slider(title="Window (points)", start=10, end=200, value=100, step=10)


def on_window_change(attr, old, new):
    # new is the slider value; rebuild what depends on it
    source.data = compute_data(window=new)


window.on_change("value", on_window_change)
curdoc().add_root(column(window, p))

Assigning a new dictionary to source.data replaces the whole table and the browser redraws. This is the server-side counterpart of the CustomJS callbacks in Bokeh Tools, Hover and Widgets: the same widgets, but the code runs in Python, so it can use pandas, NumPy, a database or any library you can install.

The price is a network round trip for every interaction and a server that must stay up. Choose CustomJS for small, visual interactions and the server for data-heavy ones.

sequenceDiagram
    participant B as Browser (BokehJS)
    participant S as Bokeh server
    participant Y as Your Python callback
    B->>S: slider value changed
    S->>Y: on_change(attr, old, new)
    Y->>S: update source.data
    S-->>B: send only the changed property
    B->>B: redraw the glyphs

In a server app the browser reports events and the server pushes back the changes.

Streaming: stream()

Replacing source.data for every new reading would resend the entire table each time. For a chart that has accumulated a thousand points, adding one more would send 1,001 rows. The method stream() sends only the new rows and BokehJS appends them:

Python
source.stream({"step": [11], "value": [3.2]})

The rules: you pass a dictionary with every column of the source and the same number of values in each (one or many rows). A missing column or mismatched lengths are errors, because every row must be complete. The optional rollover argument sets the maximum number of rows to keep. When the table grows past it, the oldest rows are dropped, which gives you a rolling window with constant memory:

Python
source.stream(new_rows, rollover=200)

Without rollover a live chart grows without limit, getting slower and using more memory in the browser, which is a classic bug in long-running dashboards.

Updating rows in place: patch()

stream() appends. When existing rows change, for example a corrected value or a live-updated bar, use patch(). It takes a dictionary of column name to a list of (index, new_value) pairs, and it sends only those cells:

Python
source.patch({"value": [(3, 9.9), (4, 8.1)]})

Slices are allowed in place of an index, with a list of values: {"value": [(slice(0, 3), [1, 2, 3])]}. Patching is the efficient way to animate a bar chart where only a few bars change per update.

The first stand-in implements the three operations as a small class. It counts how many cell values would travel to the browser for each style, so the saving is visible.

JS stream, patch and rollover on a source (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Run it and compare the two counts: replacing the whole table sends a number of cells that grows with every step, while streaming sends a constant amount per step. The last lines show the two rules of stream(): all columns are required, and the rollover keeps a fixed window.

A live-data loop

Real streaming apps are loops of "something produces new data, a callback converts it to rows, stream appends". The data source might be a sensor, a message queue, a websocket client or a database poll. Keep the callback quick: it runs on the server's event loop, so a slow query inside add_periodic_callback freezes updates for that session (and others on the same process). For slow work, run it in a thread or a separate process and hand the result back with curdoc().add_next_tick_callback(...), which is the safe way to touch the document from another thread.

The second stand-in simulates the whole loop with a fake clock, so the output is the same on every run. A seeded random generator makes the "sensor", a periodic callback appends one reading per tick, and a rolling mean and a text sparkline show the window.

JS A periodic callback feeding a rolling window (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The row count grows to 8 and then stays there, which is what rollover=8 guarantees. The sparkline always shows the last eight readings.

Deploying a Bokeh server app

bokeh serve is also the production entry point, but a few details differ from a plain web app:

  • WebSocket origins. The server refuses WebSocket connections from host names it does not know. Pass the public name with --allow-websocket-origin=your.domain (repeat for several).
  • Reverse proxy. Put nginx or another proxy in front for HTTPS, and make sure it forwards WebSocket upgrade requests. Use --prefix if the app lives under a URL path.
  • Sessions use memory. Every open tab is a live document in server memory. Limit rollover, close idle sessions with the server's session timeout options, and run several processes (--num-procs) if you need more capacity.
  • Embedding. bokeh.embed.server_document returns a script tag that embeds a running app inside another web page, such as a Flask or Django template.

If you would rather write the dashboard layer in Python with a different model, compare Dashboards with Dash and Callbacks. Dash and Bokeh server solve the same "Python callback" problem with different designs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does curdoc() return in a Bokeh server app?

    Each browser session has its own document. You attach layouts with add_root and callbacks with add_periodic_callback or widget on_change handlers.
  2. 2. What is the main advantage of source.stream() over assigning a new source.data?

    stream() appends rows and transmits just those, so the cost of an update stays small even when the table is large.
  3. 3. What does rollover=200 do?

    Rollover trims the oldest rows after each stream call, giving a rolling window with bounded memory.
  4. 4. Which call changes two existing cells of the value column in place?

    patch takes a dictionary of column names to (index, new_value) pairs and sends only those cells. stream appends new rows instead.
  5. 5. A long database query runs inside a periodic callback and the chart freezes. What is a good fix?

    Callbacks run on the server's event loop, so slow work blocks it. A thread can do the work, and add_next_tick_callback applies the result to the document safely.

Summary

  • bokeh serve app.py runs a Python process that keeps each browser session's document in sync with BokehJS.
  • Every session runs your script and gets its own curdoc(); attach layouts with add_root and timers with add_periodic_callback.
  • Widgets use on_change(attr, old, new) callbacks in Python; use CustomJS when no server is needed.
  • stream(rows, rollover=n) appends rows efficiently and keeps a rolling window; patch() changes individual cells.
  • Keep callbacks fast, use threads with add_next_tick_callback for slow work, and set --allow-websocket-origin when deploying.
  • The server code is read-only here; the runnable examples are JavaScript stand-ins for stream, patch, rollover and the callback loop.

Next: Altair and the Grammar of Graphics.