Performance¶
SQLSpec adds little overhead above the underlying database drivers. This page covers statement caching, compiled wheels, typed hydration, and columnar fetches.
Per-Config Statement Caching¶
Every adapter config (AsyncpgConfig, SqliteConfig, OracleAsyncConfig, etc.) owns a thread-safe StatementCacheHolder shared across all sessions opened via config.provide_session().
On the first execution of a SQL string, SQLSpec parses it with SQLGlot, compiles dialect placeholders, and caches the result. Later executions of the same SQL in any session from that config take a fast path:
- No SQLGlot re-parsing; the cached AST is shared and copied only if a caller mutates
.expression. SQLResult.statementis built lazily, so read queries do not allocateSQLwrappers unless you inspect.statement.enable_sqlcommenter=Trueand activeObservabilityConfigspans or observers keep the fast path.
Always open sessions with config.provide_session() or spec.provide_session(config) rather than instantiating *Driver(connection=...) directly; direct driver construction allocates an unshared cache per call.
flowchart LR
First["1st Execution: SQL String"] --> Parse["SQLGlot Parse + Dialect Compile"]
Parse --> Holder["Config StatementCacheHolder"]
Next["Subsequent Sessions: Same SQL"] --> Holder
Holder --> Fast["Direct Cursor / Wire Fast Path"]
Writing Cache-Friendly Call Shapes¶
Pass SQL strings with keyword arguments, a single parameter dictionary, or a positional tuple so calls match the direct cache key without creating per-call SQL string variants:
from sqlspec import SQLSpec
from sqlspec.adapters.sqlite import SqliteConfig
spec = SQLSpec()
config = spec.add_config(
SqliteConfig(connection_config={"database": ":memory:"})
)
with spec.provide_session(config) as session:
session.execute(
"""
CREATE TABLE accounts (
id INTEGER PRIMARY KEY,
region TEXT,
balance INTEGER
)
"""
)
session.execute_many(
"INSERT INTO accounts (region, balance) VALUES (?, ?)",
[("us-east", 500), ("eu-west", 900)],
)
for region in ("us-east", "eu-west"):
rows = session.select(
"SELECT id, balance FROM accounts WHERE region = :region",
region=region,
)
assert len(rows) == 1
Configuring and Inspecting Caches and Telemetry¶
SQLSpec and sqlspec.core expose global cache size controls, hit/miss statistics, cache eviction helpers, and aggregated telemetry snapshots:
| Method / Function | Purpose |
|---|---|
SQLSpec.configure_cache(sql_cache_size=..., fragment_cache_size=..., optimized_cache_size=..., compiled_cache_enabled=...) |
Tunes the global LRU capacities and feature flags for statement, fragment, and optimized AST caches. |
SQLSpec.get_cache_stats() / SQLSpec.reset_stats_only() |
Returns current cache hit/miss counters or resets statistics without evicting cached entries. |
clear_all_caches() (from sqlspec.core import clear_all_caches) |
Evicts all global statement, builder, fragment, and parameter caches across configs. |
spec.clear_sql_cache() |
Clears the SQLFileLoader cache on a specific SQLSpec registry instance. |
spec.telemetry_snapshot() |
Returns aggregated lifecycle, pool, and loader diagnostics across all configs registered on spec. |
from sqlspec import SQLSpec
from sqlspec.core import clear_all_caches
SQLSpec.configure_cache(sql_cache_size=2048, fragment_cache_size=1024)
stats = SQLSpec.get_cache_stats()
SQLSpec.reset_stats_only()
spec = SQLSpec()
snapshot = spec.telemetry_snapshot()
spec.clear_sql_cache()
clear_all_caches()
Pre-Compiled MyPyC Wheels and SQLGlot C Extension¶
SQLSpec compiles its hot-path modules (across core, driver, builder, dialects, migrations, data_dictionary, storage, service, observability, utils, extensions, and each database adapter) to native C extensions with mypyc.
Compatible precompiled wheels provide SQLSpec's native modules. The optional
mypyc extra installs sqlglot[c]; it does not compile SQLSpec itself.
The performance extra installs msgspec and librt runtime helpers.
Combine them when your deployment needs both:
Fast Typed Hydration with msgspec.Struct¶
When mapping rows into Python objects on latency-critical hot paths, msgspec.Struct(..., frozen=True, gc=False) avoids per-row Pydantic validator overhead and omits CPython's PyGC_Head cyclic garbage-collection tracking header:
import msgspec
class OrderSummary(msgspec.Struct, frozen=True, gc=False):
order_id: int
customer_id: int
total_cents: int
For serialization on hot HTTP or queue paths, pair msgspec.Struct with SQLSpec's centralized msgspec-backed JSON encoders (sqlspec.utils.serializers).
Batched Writes and Arrow Thresholds¶
- Prefer
execute_manyorselect_to_arrowover row loops: Single-pass parameter preparation inexecute_manyavoids repeated per-row compilation. - DuckDB small results and container memory: DuckDB result sets expected to return fewer than 64 rows, and columns with types that do not round-trip through Arrow, materialize with
fetchall()to skip Arrow conversion overhead; larger scans stream through Arrow. In containers,DuckDBConfigreads cgroup v1/v2 memory limits so the defaultmemory_limitis capped at a fraction (0.8by default) of the container quota rather than host RAM. - Large Analytical Exports and Streaming Coercion: Use
session.select_to_arrow(..., return_format="batches"),pipeline.read_arrow_batches(...), orsession.select_stream(..., chunk_size=1000)to bound resident memory on multi-million-row reads and bulk loads.
Summary Checklist¶
| Lever | Recommendation |
|---|---|
| Session Creation | Always use config.provide_session() / spec.provide_session(config) so StatementCacheHolder is shared across requests. |
| Compiled Runtime | Install sqlspec[mypyc,performance] to pair compiled sqlspec modules with sqlglot[c] and msgspec. |
| Row Models | Use msgspec.Struct(..., frozen=True, gc=False) or TypedDict on latency-sensitive endpoints. |
| Parameter Style | Pass a dict/kwargs or tuple directly to session.select(sql, ...) so calls hit the direct statement cache path. |
| Bulk Reads/Writes | Use execute_many for multi-row DML and select_to_arrow / load_from_arrow for columnar workloads. |