fastdtw developer on retainer: calling fastdtw.fastdtw() twice computes full O(N) alignment twice — distance from first call discarded — path from second call — batch job doubles in duration — 3 weeks — fastdtw developer on monthly retainer
fastdtw 0.3.4 • Python 3.11; fastdtw.fastdtw(query, ref)[0] for distance then fastdtw.fastdtw(query, ref)[1] for path; fastdtw has no internal cache; each call runs full O(N) algorithm from scratch; 100,000 comparison pairs → 130,000 DTW computations; batch job 80 s → 104 s; deadline misses under load; fix: distance, path = fastdtw.fastdtw(query, ref) • Northfield Fastdtw Ltd. (audio fingerprinting; 100,000 DTW comparisons per batch; 1.5h retainer engagement)
Northfield Fastdtw Ltd. built an audio fingerprinting service for melody similarity search. The pipeline compared 13-coefficient MFCC sequences for 100,000 clip pairs per batch job, using fastdtw (0.3.4) with scipy.spatial.distance.euclidean as the per-frame distance function. Each batch was scheduled hourly. The comparison logic was split across two functions: a primary filter function that called fastdtw.fastdtw(query_mfcc, ref_mfcc, dist=euclidean)[0] to retrieve the similarity distance and compare it against a threshold, and a secondary visualization function that was called only when a match was confirmed and retrieved the alignment path via fastdtw.fastdtw(query_mfcc, ref_mfcc, dist=euclidean)[1]. The design intention was reasonable: compute the cheap threshold check first, only retrieve the path when necessary. The flaw was that fastdtw has no internal result cache — every call to fastdtw.fastdtw() runs the complete O(N) FastDTW algorithm from scratch, regardless of whether the same (query, ref) pair was computed moments earlier. Because approximately 30% of the 100,000 pairs passed the similarity threshold, 30,000 pairs triggered a second full fastdtw computation in addition to the first pass, raising total fastdtw invocations per batch to 130,000. Batch duration grew from the designed 80 seconds to approximately 104 seconds and began intermittently missing the hourly deadline under elevated load.
The team spent three weeks investigating the performance regression. CPU profiling confirmed that fastdtw calls accounted for approximately 70% of batch CPU time. The team benchmarked different dist function implementations (pure Python lambda, C-accelerated euclidean, cython wrapper), tested downgrading and upgrading the fastdtw package version, and profiled the MFCC extraction step as a potential bottleneck — none of which addressed the root cause because the problem was not the per-call efficiency of fastdtw but the total number of calls. The fastdtw.fastdtw() function always returns a 2-tuple (distance, path): it computes both the cumulative path cost and the aligned index list as part of the same O(N) coarse-to-fine algorithm, and there is no way to request distance-only or path-only. When the developer retrieved [0] for the distance, the path was computed and silently discarded. When the developer subsequently retrieved [1] for the path, the entire algorithm — cost matrix allocation, coarse-scale DTW, fine-scale path tracing — ran again at full O(N) cost, returning the same path that had just been discarded. The fix was a single-line change: replace the two separate subscript calls with one tuple unpack, distance, path = fastdtw.fastdtw(query_mfcc, ref_mfcc, dist=euclidean), and thread both values through the pipeline so the path was available to the visualization function without a second computation.
The annotated buggy and fixed comparison loop:
# Northfield Fastdtw Ltd. — fastdtw 0.3.4 double-call fix
# fastdtw 0.3.4; Python 3.11; NumPy 1.24; scipy 1.11
# Audio fingerprinting; 100,000 DTW comparison pairs per hourly batch
#
# Problem: developer calls fastdtw.fastdtw(x, y)[0] for distance
# and fastdtw.fastdtw(x, y)[1] separately for path — two calls per matching pair
# fastdtw has no internal cache; each call runs full O(N) algorithm from scratch
# 30% of 100,000 pairs match → 30,000 extra fastdtw calls per batch
# total: 130,000 fastdtw calls × 0.8ms each = 104s (designed: 80s)
# batch deadline misses under elevated load; 3 weeks
# Fix: unpack (distance, path) from a single fastdtw call
import numpy as np
import librosa
import fastdtw
from scipy.spatial.distance import euclidean
HOP_LENGTH = 512
SR = 22050
N_MFCC = 13
SIMILARITY_THRESHOLD = 8.5 # mean per-frame DTW distance
def extract_mfcc(audio_path: str) -> np.ndarray:
"""Load audio and extract MFCC, returning (n_frames, n_mfcc) array."""
y, _ = librosa.load(audio_path, sr=SR)
mfcc = librosa.feature.mfcc(y=y, sr=SR, n_mfcc=N_MFCC, hop_length=HOP_LENGTH)
return mfcc.T # librosa: (n_mfcc, n_frames) → (n_frames, n_mfcc) for fastdtw
# ── BUGGY batch comparison ────────────────────────────────────────────────────
def process_pair_buggy(
query_mfcc: np.ndarray,
ref_mfcc: np.ndarray,
) -> tuple[bool, list]:
"""BUGGY: calls fastdtw twice — O(N) alignment computed twice per matching pair."""
# First call: get distance only — path computed internally, then discarded
dist = fastdtw.fastdtw(query_mfcc, ref_mfcc, dist=euclidean)[0]
per_frame_dist = dist / max(len(query_mfcc), len(ref_mfcc))
if per_frame_dist < SIMILARITY_THRESHOLD:
# BUG: second call recomputes the full O(N) FastDTW algorithm from scratch
# fastdtw has no internal cache; (query_mfcc, ref_mfcc) reprocessed entirely
# for 30% match rate on 100,000 pairs: 30,000 extra fastdtw calls per batch
# each call ≈ 0.8ms → 24 extra seconds per batch → deadline misses under load
path = fastdtw.fastdtw(query_mfcc, ref_mfcc, dist=euclidean)[1]
return True, path
return False, []
# ── FIXED batch comparison ────────────────────────────────────────────────────
def process_pair(
query_mfcc: np.ndarray,
ref_mfcc: np.ndarray,
) -> tuple[bool, list]:
"""FIXED: unpack (distance, path) from a single fastdtw call."""
# FIX: fastdtw always computes both distance and path in one O(N) pass
# Unpack both return values at once — eliminates the second call entirely
# Total fastdtw calls per batch: 100,000 (not 130,000); duration: 80s (not 104s)
distance, path = fastdtw.fastdtw(query_mfcc, ref_mfcc, dist=euclidean)
per_frame_dist = distance / max(len(query_mfcc), len(ref_mfcc))
if per_frame_dist < SIMILARITY_THRESHOLD:
return True, path # path already computed above — no second call needed
return False, []
# ── Throughput validation ─────────────────────────────────────────────────────
def validate_single_call_invariant(
test_mfcc_a: np.ndarray,
test_mfcc_b: np.ndarray,
) -> None:
"""Assert fastdtw returns (distance, path) tuple from a single call."""
result = fastdtw.fastdtw(test_mfcc_a, test_mfcc_b, dist=euclidean)
assert isinstance(result, tuple) and len(result) == 2, (
f"fastdtw.fastdtw() should return 2-tuple (distance, path), got {type(result)}"
)
distance, path = result
assert isinstance(distance, float), f"distance should be float, got {type(distance)}"
assert isinstance(path, list), f"path should be list of (i,j) tuples, got {type(path)}"
# Self-comparison sanity check
self_result = fastdtw.fastdtw(test_mfcc_a, test_mfcc_a, dist=euclidean)
assert self_result[0] == 0.0, (
f"Self-comparison distance should be 0.0, got {self_result[0]}"
)
How calling fastdtw.fastdtw()[0] and fastdtw.fastdtw()[1] in separate functions doubles the O(N) computation for every matching pair — and the correct single-call unpack pattern for fastdtw pipelines
The core failure combines two independent factors. First, fastdtw’s API always returns both the distance and the path as a tuple, because the FastDTW algorithm computes them jointly as part of the same O(N) coarse-to-fine alignment procedure. The distance cannot be computed without tracing the path, and the path is always traced even if the caller intends to discard it. This means that subscripting [0] to retrieve only the distance is exactly as expensive as subscripting [1] to retrieve only the path: in both cases, the full alignment has been computed. Second, the split-function design — one function for threshold filtering, another for path retrieval — created a code structure where the second call looked syntactically similar to the first and there was no visible indication in either function that the other function had already computed the same result. This is a common pattern in Python when a function returns multiple values: developers who don’t need all return values on the first use often retrieve them piecemeal later, unaware that the second retrieval is as expensive as a full recomputation. The fix had two parts: replace both separate subscript calls with a single tuple unpack (distance, path = fastdtw.fastdtw(query_mfcc, ref_mfcc, dist=euclidean)) and thread both values through the calling code so the path was available without a second call. Additionally, a throughput monitoring assertion was added that logs total fastdtw calls per batch and alerts if the count exceeds 1.1× the expected number of pairs, catching future regressions of this pattern. After applying the fix, total fastdtw calls per batch dropped from 130,000 to 100,000, batch duration dropped from 104 seconds to 80 seconds, and deadline misses stopped entirely. The retainer engagement was 1.5h: 0.5h triage (instrument fastdtw call count per batch; confirm 130,000 calls for 100,000 pairs; trace extra 30,000 to second function called for matching pairs); 0.5h root cause (fastdtw always returns (distance, path) as a 2-tuple; no cache; second subscript call re-runs full O(N); distance from first call discarded silently); 0.5h fix (single tuple unpack; throughput assertion added; batch duration 104 s → 80 s; deadline misses stop; 1.5h total). Hours logged to HourTab with per-session breakdown.
Related retainer posts
- dtw-python developer on retainer — dtw-python 1.3.0; Python 3.11;
.distanceaccumulates over alignment path; longer recordings always exceed threshold calibrated on short clips; similarity search returns no results for 60% of catalog; fix:normalizedDistance; 3 weeks — 2.0h - librosa developer on retainer — librosa 0.10.1; Python 3.10;
librosa.load()defaultsr=22050resamples audio silently; model trained at 44100 Hz receives 22050 Hz features at inference; classification accuracy 0.61 not 0.84; 3 weeks — 2.0h - nnAudio developer on retainer — nnAudio 0.3.2; Python 3.10; PyTorch 1.13;
CQT1992v2returns(batch, 84, 130);cqt.Ton 3-D reverses all dims to(130, 84, 1); LSTM receives wrong shape; chord recognition 23% not 76%; 3 weeks — 2.0h
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 →