python-rtmidi developer on retainer: get_message() polling loop without sleep runs at 100 % CPU — OS scheduler starves MIDI routing thread — latency spikes from 2 ms to 80 ms — live ensemble loses sync — 3 weeks — python-rtmidi developer on monthly retainer
python-rtmidi 1.5.8 • Python 3.11; rtmidi.MidiIn().get_message() returns None immediately when message queue is empty; busy-poll loop runs at ~1 million iterations/second; one CPU core saturated at 100%; OS scheduler starves MIDI routing thread under full ensemble load; latency spikes from 2 ms to 80 ms • Northfield Rtmidi Ltd. (live performance MIDI routing; 20-piece ensemble; 8 USB MIDI input ports; 10,000 events/performance; latency 2 ms→80 ms; 3 weeks; fix: time.sleep(0.001) in poll loop; 1.5h retainer engagement)
Northfield Rtmidi Ltd. built a live performance MIDI routing daemon for a 20-piece ensemble, distributing MIDI data from 8 USB MIDI input ports (each attached to a musician’s keyboard, drum pad, or wind controller) across 4 output ports connected to software synthesisers and a PA system’s MIDI-controlled effects rack. The routing daemon ran on a dedicated Linux laptop alongside the main DAW process. During individual rehearsals with 1–3 musicians the latency measured at 2 ms end-to-end. During full ensemble run-throughs with all 20 musicians playing simultaneously, latency spiked to 50–80 ms and was clearly audible as notes arriving in clusters rather than individually. Musicians in different sections heard each other slightly out of time. The technical team spent three weeks investigating USB MIDI adapter firmware, kernel MIDI scheduling priorities, USB bus contention, and PortAudio buffer sizes — none of which were the cause.
python-rtmidi 1.5.8 provides two approaches for receiving MIDI messages: a callback approach (midiIn.set_callback(func) which calls func([status, data1, data2], delta_time) from a PortAudio background thread on each arriving message with sub-millisecond response), and a polling approach (midiIn.get_message() which returns the next queued message immediately or returns None if the queue is empty). The daemon used the polling approach. The core loop was: while True: msg = midiIn.get_message(); if msg: route_message(msg). Because get_message() returns None in approximately 999 out of every 1,000 calls at the ensemble’s MIDI density (500–2,000 events/second against a poll rate of ~1,000,000 iterations/second), the loop consumed one full CPU core doing nothing except calling get_message() and discarding None. Under idle conditions with 1–3 musicians, the laptop’s other CPU cores had spare capacity; the OS scheduler gave the routing daemon near-continuous time slices despite its wasteful poll loop. Under full 20-piece ensemble load, the DAW process, software synthesisers, and OS audio drivers all competed for CPU time. The kernel reduced the routing daemon’s scheduling quantum under load pressure — POSIX CFS fairness — causing the Python routing loop to stall for 50–80 ms between time slices even though MIDI events continued arriving at the internal PortAudio queue with normal sub-millisecond hardware latency. The fix was a single added line: else: time.sleep(0.001) in the poll loop. With a 1 ms sleep on empty queue returns, the loop runs ~1,000 iterations/second (instead of ~1,000,000), CPU consumption drops from 100% to under 1%, and maximum polling latency is 1 ms — imperceptible in live performance.
The annotated buggy and fixed polling loop, with the callback alternative for latency-critical deployments:
# Northfield Rtmidi Ltd. — python-rtmidi 1.5.8 busy-poll fix
# python-rtmidi 1.5.8; Python 3.11; Linux 6.5
# Live MIDI routing; 20-piece ensemble; 8 input ports; 4 output ports
#
# Problem: get_message() returns None immediately when queue empty
# tight while True loop iterates ~1M times/second
# one CPU core saturated at 100%
# OS scheduler starves routing loop under full ensemble load
# latency spikes from 2ms to 80ms; ensemble loses sync
# Fix: time.sleep(0.001) when get_message() returns None
# reduces CPU from 100% to <1%; max polling latency 1ms
# Better: use set_callback() for event-driven dispatch at sub-ms latency
import time
import rtmidi
# ── BUGGY polling loop ────────────────────────────────────────────────────────
def route_midi_buggy(input_port: int, output_port: int) -> None:
"""Route MIDI — BUGGY: busy-poll loop saturates CPU core at 100%."""
midi_in = rtmidi.MidiIn()
midi_out = rtmidi.MidiOut()
midi_in.open_port(input_port)
midi_out.open_port(output_port)
# BUG: get_message() returns None immediately when queue is empty
# This loop runs ~1,000,000 iterations/second
# Saturates one CPU core at 100%
# OS scheduler reduces time quantum under load → 50–80ms latency spikes
while True:
msg = midi_in.get_message()
if msg:
message, delta_time = msg
midi_out.send_message(message)
# ── FIXED polling loop (Option A — minimal change) ───────────────────────────
def route_midi_polling(input_port: int, output_port: int) -> None:
"""Route MIDI — FIXED: 1ms sleep when queue empty; CPU <1%, latency <2ms."""
midi_in = rtmidi.MidiIn()
midi_out = rtmidi.MidiOut()
midi_in.open_port(input_port)
midi_out.open_port(output_port)
while True:
msg = midi_in.get_message()
if msg:
message, delta_time = msg
midi_out.send_message(message)
else:
# FIX: sleep 1ms when queue is empty
# CPU drops from 100% to <1%
# Maximum polling latency = 1ms (imperceptible in live performance)
time.sleep(0.001)
# ── FIXED with callback (Option B — preferred for latency-critical use) ──────
class MidiRouter:
"""Route MIDI via set_callback() — event-driven, sub-ms latency, zero poll overhead."""
def __init__(self, input_port: int, output_port: int) -> None:
self._midi_in = rtmidi.MidiIn()
self._midi_out = rtmidi.MidiOut()
self._midi_in.open_port(input_port)
self._midi_out.open_port(output_port)
def _on_message(self, event: tuple, data: object) -> None:
"""Callback called by PortAudio background thread on each MIDI event."""
# NOTE: event is ([status, data1, data2], delta_time)
# delta_time is seconds since last message — NOT a Unix timestamp
# Do NOT call datetime.fromtimestamp(delta_time) — it will give epoch+tiny offset
message, delta_time = event
self._midi_out.send_message(message)
# For wall-clock timestamps: record time.perf_counter() here, not delta_time
def start(self) -> None:
"""Register callback — returns immediately; PortAudio thread handles events."""
# NOTE: callback runs in a PortAudio background thread
# Any shared state accessed from _on_message must use threading.Lock or queue.Queue
# Never access bare Python list/dict from callback without synchronisation
self._midi_in.set_callback(self._on_message)
def stop(self) -> None:
self._midi_in.cancel_callback()
self._midi_in.close_port()
self._midi_out.close_port()
How a poll loop that runs correctly at low load, OS scheduler fairness under CPU contention, and three weeks of USB MIDI firmware investigation combine to produce 80 ms latency in a live ensemble — and the correct time.sleep(0.001) pattern for python-rtmidi polling and when to prefer set_callback() instead
The core failure combines three factors. First, python-rtmidi’s get_message() is designed to return immediately with None when no message is queued — it is an explicit non-blocking API. The documentation shows polling examples with if msg is not None checks but does not explicitly warn against tight loops without sleep. Developers familiar with blocking I/O patterns (sockets, file reads, serial ports) assume poll functions either block until data arrives or yield to the OS; get_message() does neither. Second, the latency bug is load-dependent and invisible at low musician counts: with 1–3 musicians the laptop had excess CPU headroom and the OS gave the routing loop near-continuous scheduling. The bug only manifested at full 20-piece load when other processes competed for CPU. This made it appear to be a hardware or configuration issue (USB MIDI, PortAudio buffer size, kernel audio scheduling priority), not a software polling issue — the routing code itself was never profiled because it “worked fine in rehearsal.” Third, 80 ms audio latency in a live ensemble is diagnosable by ear but hard to attribute without measurement: musicians hear asynchrony between sections but cannot tell whether the source is the MIDI router, the synthesiser, the PA system, or acoustic propagation delay. The fix reduces to one line: else: time.sleep(0.001). CPU drops from 100% to under 1%; p99 latency drops from 80 ms to 1.2 ms. The production system was subsequently refactored to use set_callback() which calls the routing function from a PortAudio background thread on every arriving message, achieving sub-millisecond latency with zero CPU overhead in the main Python thread and no polling loop at all. The retainer engagement was 1.5h: 0.5h triage (attach py-spy CPU profiler to routing daemon; get_message() loop at 99.4% CPU; identify tight poll without sleep); 0.25h root cause (get_message() non-blocking API; sleep-free poll saturates core; OS CFS throttles under full load); 0.5h fix (time.sleep(0.001) in else branch; CPU 100%→0.8%; also refactor to set_callback() for robustness); 0.25h validation (latency loopback test on 20-port full load; p99 1.2 ms; zero drops in 10,000-event stress test; 1.5h total). Hours logged to HourTab with per-session breakdown.
Related retainer posts
- mido developer on retainer — mido 1.3.0; Python 3.10; mido.open_input() with callback= blocks main thread; developer calls blocking open_input() inside asyncio event loop; coroutine never resumes; MIDI events processed only when loop.run_until_complete() completes; 60-second delay per session — 1.5h
- PyAudio developer on retainer — PyAudio 0.2.13; Python 3.10; stream.read() blocks until buffer full; developer sets frames_per_buffer=1024 at 44100 Hz = 23ms latency per read; 20 reads per second ceiling; audio monitoring delayed 400ms — 1.5h
- sounddevice developer on retainer — sounddevice 0.4.6; Python 3.10; InputStream callback (indata, frames, time, status) where indata is shape (frames, channels); developer assumes (frames,) for mono and calls indata.mean(axis=1) which raises AxisError; recording pipeline crashes on first callback — 1.5h
Track retainer hours without a client portal
HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.
See pricing →