{"id":505657,"date":"2026-12-01T21:12:45","date_gmt":"2026-12-01T18:12:45","guid":{"rendered":"https:\/\/savepearlharbor.com\/?p=505657"},"modified":"2026-12-01T21:12:45","modified_gmt":"2026-12-01T18:12:45","slug":"","status":"publish","type":"post","link":"https:\/\/savepearlharbor.com\/?p=505657","title":{"rendered":"SQLite Had a 10 ms Timeout. This Query Took 221 ms"},"content":{"rendered":"<div xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\">\n<p>The connection had a ten-millisecond timeout. The query took 221 milliseconds and returned successfully. That sounds like a broken timeout until you look at what Python&#8217;s SQLite setting actually limits.<\/p>\n<p><code>sqlite3.connect(timeout=...)<\/code> controls how long a connection waits when another connection holds a database lock. It does not set a deadline for a query that has already started running. The difference matters if an endpoint builds a larger join than expected or lets users filter data in expensive ways.<\/p>\n<p>To make the distinction visible, the experiment uses a deliberately clumsy query. One in-memory table holds 5,000 rows. Counting a cross join of that table with itself gives SQLite 25 million row pairs to process. There is one connection, no competing writer, and nothing to wait for except the query&#8217;s own work.<\/p>\n<figure class=\"full-width \"><img decoding=\"async\" src=\"https:\/\/habrastorage.org\/r\/w1560\/extt\/f9\/08\/71\/f90871838cdb2fdc1d2abc0c2d3d2300.png\" width=\"1187\" height=\"659\" sizes=\"auto, (max-width: 780px) 100vw, 50vw\" srcset=\"https:\/\/habrastorage.org\/r\/w780\/extt\/f9\/08\/71\/f90871838cdb2fdc1d2abc0c2d3d2300.png 780w,&#10;       https:\/\/habrastorage.org\/r\/w1560\/extt\/f9\/08\/71\/f90871838cdb2fdc1d2abc0c2d3d2300.png 781w\" loading=\"lazy\" decode=\"async\"\/><\/figure>\n<h3>The query that ignored the timeout<\/h3>\n<p>Here is the setup:<\/p>\n<pre><code>import sqlite3db = sqlite3.connect(':memory:', timeout=0.010)db.execute('CREATE TABLE data (n INTEGER)')db.executemany(    'INSERT INTO data VALUES (?)',    ((i,) for i in range(5_000)),)db.commit()result = db.execute(    'SELECT COUNT(*) FROM data AS a CROSS JOIN data AS b').fetchone()[0]assert result == 25_000_000<\/code><div class=\"code-explainer\"><a href=\"https:\/\/sourcecraft.dev\/\" class=\"tm-button code-explainer__link\" style=\"visibility: hidden;\"><span class=\"sc-logo-wrapper\"><\/span><\/a><\/div><\/pre>\n<p>The ten-millisecond setting never comes into play. No other connection holds a lock. The query is free to run until it finishes.<\/p>\n<p>It did finish on every attempt. Across seven runs, the median was <strong>221.0 ms<\/strong>; individual runs took <strong>217.7 to 226.1 ms<\/strong>. The database returned the correct count each time.<\/p>\n<p>This is a local measurement on Python 3.12.16 and SQLite 3.53.1. A different machine will produce different timings. The part to notice is that the query continued well past ten milliseconds without encountering a lock timeout.<\/p>\n<h3>Give the work its own deadline<\/h3>\n<p>For an execution budget, SQLite offers a progress callback. It checks in after a chosen number of virtual-machine instructions. The callback can tell SQLite to interrupt the operation.<\/p>\n<p>The next run kept the same connection and the same query. It added a 25-millisecond budget, checked every 1,000 instructions:<\/p>\n<pre><code>import timebudget = 0.025started = time.perf_counter()def progress():    return int(time.perf_counter() - started &gt;= budget)db.set_progress_handler(progress, 1_000)try:    db.execute(        'SELECT COUNT(*) FROM data AS a CROSS JOIN data AS b'    ).fetchone()except sqlite3.OperationalError as exc:    if str(exc) != 'interrupted':        raisefinally:    db.set_progress_handler(None, 0)<\/code><div class=\"code-explainer\"><a href=\"https:\/\/sourcecraft.dev\/\" class=\"tm-button code-explainer__link\" style=\"visibility: hidden;\"><span class=\"sc-logo-wrapper icon-only\"><\/span><\/a><\/div><\/pre>\n<p>This time the count did not complete. Seven runs were interrupted after a median of <strong>25.0 ms<\/strong>, with observed times from <strong>25.0 to 25.1 ms<\/strong>. The connection still worked afterward: a simple count of the original table returned 5,000 rows.<\/p>\n<p>That narrow range is a property of this particular run, not a promise of precise cancellation. SQLite invokes the callback at checkpoints. If those checkpoints are farther apart, the operation can pass its deadline before the next check. Calling back more often has a cost as well. The interval needs testing against the actual workload.<\/p>\n<h3>The detail that can bite later<\/h3>\n<p>The progress callback is installed on the <strong>connection<\/strong>, not on a single SQL string. Imagine returning that connection to a pool while the callback still holds a deadline from the previous request. A later, unrelated query could then be interrupted. Removing the handler in <code>finally<\/code> is part of the example for that reason.<\/p>\n<p>The 25-millisecond clock also starts immediately before this query. It says nothing about time spent acquiring a connection, doing earlier work, or returning an HTTP response. In a request handler, the remaining request time would need to be passed into the query budget deliberately. A client disconnecting does not make this progress function notice by itself.<\/p>\n<p>None of this makes 25 milliseconds a sensible default. The cross join is deliberately excessive, and the experiment does not model production traffic. It establishes a smaller, useful point: <strong>the 10 ms connection timeout did not stop a 221 ms query, while a separate execution budget interrupted it near 25 ms<\/strong>.<\/p>\n<p>The next time an endpoint runs longer than its configured SQLite timeout, check which clock that setting controls. Waiting for a lock and executing SQL are two different kinds of waiting. Giving them separate measurements and separate limits makes the behavior a lot less surprising.<\/p>\n<\/div>\n<p>\u0441\u0441\u044b\u043b\u043a\u0430 \u043d\u0430 \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b \u0441\u0442\u0430\u0442\u044c\u0438 <a href=\"https:\/\/habr.com\/ru\/articles\/1114724\/\">https:\/\/habr.com\/ru\/articles\/1114724\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The connection had a ten-millisecond timeout. The query took 221 milliseconds and returned successfully. That sounds like a broken timeout until you look at what Python&#8217;s SQLite setting actually limits.sqlite3.connect(timeout=&#8230;) controls how long a connection waits when another connection holds a database lock. It does not set a deadline for a query that has already started running. The difference matters if an endpoint builds a larger join than expected or lets users filter data in expensive ways.To make the distinction visible, the experiment uses a deliberately clumsy query. One in-memory table holds 5,000 rows. Counting a cross join of that table with itself gives SQLite 25 million row pairs to process. There is one connection, no competing writer, and nothing to wait for except the query&#8217;s own work.The query that ignored the timeoutHere is the setup:import sqlite3db = sqlite3.connect(&#8216;:memory:&#8217;, timeout=0.010)db.execute(&#8216;CREATE TABLE data (n INTEGER)&#8217;)db.executemany(    &#8216;INSERT INTO data VALUES (?)&#8217;,    ((i,) for i in range(5_000)),)db.commit()result = db.execute(    &#8216;SELECT COUNT(*) FROM data AS a CROSS JOIN data AS b&#8217;).fetchone()[0]assert result == 25_000_000The ten-millisecond setting never comes into play. No other connection holds a lock. The query is free to run until it finishes.It did finish on every attempt. Across seven runs, the median was 221.0 ms; individual runs took 217.7 to 226.1 ms. The database returned the correct count each time.This is a local measurement on Python 3.12.16 and SQLite 3.53.1. A different machine will produce different timings. The part to notice is that the query continued well past ten milliseconds without encountering a lock timeout.Give the work its own deadlineFor an execution budget, SQLite offers a progress callback. It checks in after a chosen number of virtual-machine instructions. The callback can tell SQLite to interrupt the operation.The next run kept the same connection and the same query. It added a 25-millisecond budget, checked every 1,000 instructions:import timebudget = 0.025started = time.perf_counter()def progress():    return int(time.perf_counter() &#8212; started &gt;= budget)db.set_progress_handler(progress, 1_000)try:    db.execute(        &#8216;SELECT COUNT(*) FROM data AS a CROSS JOIN data AS b&#8217;    ).fetchone()except sqlite3.OperationalError as exc:    if str(exc) != &#8216;interrupted&#8217;:        raisefinally:    db.set_progress_handler(None, 0)This time the count did not complete. Seven runs were interrupted after a median of 25.0 ms, with observed times from 25.0 to 25.1 ms. The connection still worked afterward: a simple count of the original table returned 5,000 rows.That narrow range is a property of this particular run, not a promise of precise cancellation. SQLite invokes the callback at checkpoints. If those checkpoints are farther apart, the operation can pass its deadline before the next check. Calling back more often has a cost as well. The interval needs testing against the actual workload.The detail that can bite laterThe progress callback is installed on the connection, not on a single SQL string. Imagine returning that connection to a pool while the callback still holds a deadline from the previous request. A later, unrelated query could then be interrupted. Removing the handler in finally is part of the example for that reason.The 25-millisecond clock also starts immediately before this query. It says nothing about time spent acquiring a connection, doing earlier work, or returning an HTTP response. In a request handler, the remaining request time would need to be passed into the query budget deliberately. A client disconnecting does not make this progress function notice by itself.None of this makes 25 milliseconds a sensible default. The cross join is deliberately excessive, and the experiment does not model production traffic. It establishes a smaller, useful point: the 10 ms connection timeout did not stop a 221 ms query, while a separate execution budget interrupted it near 25 ms.The next time an endpoint runs longer than its configured SQLite timeout, check which clock that setting controls. Waiting for a lock and executing SQL are two different kinds of waiting. Giving them separate measurements and separate limits makes the behavior a lot less surprising.\u0441\u0441\u044b\u043b\u043a\u0430 \u043d\u0430 \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b \u0441\u0442\u0430\u0442\u044c\u0438 https:\/\/habr.com\/ru\/articles\/1114724\/<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[],"tags":[],"class_list":["post-505657","post","type-post","status-publish","format-standard","hentry"],"_links":{"self":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts\/505657","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=505657"}],"version-history":[{"count":0,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts\/505657\/revisions"}],"wp:attachment":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=505657"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=505657"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=505657"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}