Skip to main content

Transparent temporal coalescing and inline micro-batching for Python.

Project description

concresce 💧

Transparent temporal coalescing and inline micro-batching.

Standard solutions to N+1 database or network bottlenecks require spinning up external message queues, background workers, or complex task graphs. concresce solves this dynamically. You write the function as if it processes a single item, and the runtime transparently merges concurrent calls into a single batch in the background.

uv add concresce

The Difference

Concept Standard Async Loop Message Queues (Celery/Kafka) concresce
Network Footprint N requests for N items. 1 request for N items. 1 request for N items.
Architectural Overhead None. High (Requires external broker). None (Pure inline code).
Return Routing Native variables. Complex (Webhooks / Polling). Native variables (Futures resolve).

Usage

You need exactly two primitives: @batch to define the barrier constraint, and collect() to suspend the execution and pool data.

By default there is zero configuration: the batch window is dynamically defined by the event loop's microtask queue, and routing is handled natively by your return types. A single optional window knob is available when you need a wider collection window.

import asyncio
from concresce import batch, collect

@batch
async def fetch_user_score(user_id):
    # 1. Execution pauses here.
    # Concurrent calls inside the current event loop tick pool their `user_id`s.
    batch_ids = await collect(user_id)

    # 2. Only ONE execution path (the leader) resumes from this point.
    # The others remain safely suspended via Exception-driven control flow.
    print(f"Making 1 network call for {len(batch_ids)} users...")
    bulk_results = await db.bulk_fetch_scores(batch_ids)

    # 3. The leader returns the raw bulk list, one result per pooled item.
    # The decorator distributes the results back to the followers by index.
    return bulk_results


async def main():
    # Fire off 5 requests simultaneously
    results = await asyncio.gather(
        fetch_user_score(1),
        fetch_user_score(2),
        fetch_user_score(3),
        fetch_user_score(4),
        fetch_user_score(5)
    )

    # Returns:[100, 250, 190, 300, 120]
    print(results)

asyncio.run(main())

The window parameter

By default a batch spans a single event-loop tick: the leader yields once (await asyncio.sleep(0)) and then processes whatever pooled during that tick. That is ideal under load, but on bursty traffic the items you want to coalesce can land a few milliseconds apart, in separate ticks.

Pass a window to @batch to widen the collection window. It is a datetime.timedelta that decides how long the leader sleeps before it collects and runs the batch — every call that arrives during that window joins the same batch.

from datetime import timedelta
from concresce import batch, collect

@batch(window=timedelta(milliseconds=5))
async def fetch_user_score(user_id):
    batch_ids = await collect(user_id)
    return await db.bulk_fetch_scores(batch_ids)
  • @batch (bare) — leader sleeps 0; the batch is one event-loop tick. This is the default.
  • @batch(window=timedelta(milliseconds=5)) — leader sleeps 5 ms; everything that arrives in that window is coalesced.

Widening the window trades a little latency for larger, more efficient batches.

Core Mechanics

  • Event Loop Batching: With the default zero-length window (timedelta(0)) concresce yields exactly once to the event loop. Under heavy load, batches are large; under low load, they execute instantly. A wider window simply extends how long the leader waits before collecting.
  • Positional Routing: The leader does not call a special scatter function. It returns a list or tuple with one result per collected item, in the same order, and the system unzips it by index. Any other return type — or a sequence whose length does not match the number of callers — raises BatchRoutingError for every caller instead of hanging.
  • Fault Propagation: If the leader crashes during processing, the exception is intercepted and replicated to all suspended followers. Nobody hangs, and the stack unwinds naturally.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

concresce-5.1.0.tar.gz (4.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

concresce-5.1.0-py3-none-any.whl (5.5 kB view details)

Uploaded Python 3

File details

Details for the file concresce-5.1.0.tar.gz.

File metadata

  • Download URL: concresce-5.1.0.tar.gz
  • Upload date:
  • Size: 4.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.28 {"installer":{"name":"uv","version":"0.11.28","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"CachyOS Linux","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for concresce-5.1.0.tar.gz
Algorithm Hash digest
SHA256 793de1c833fa9c8243c75eeffb17052dcf400cdf57cf84c6d005df76a9266211
MD5 3d53b54672d730f4afc87e6d27ba57ca
BLAKE2b-256 cceb4262fb5a9ed12b7087fed8056ecba44a28a2d40d0fd36bede301d5015af6

See more details on using hashes here.

File details

Details for the file concresce-5.1.0-py3-none-any.whl.

File metadata

  • Download URL: concresce-5.1.0-py3-none-any.whl
  • Upload date:
  • Size: 5.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.28 {"installer":{"name":"uv","version":"0.11.28","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"CachyOS Linux","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for concresce-5.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5d9e09bdfb0a4ad30b639416476455c64af2bf4204a62b2344a5210ec54c7a82
MD5 82b38e08d749e4703989f79ac2194e41
BLAKE2b-256 f2497a9e09b784a84f48a9ad1361caa4001d0d5a49f62c0899bf6ab9e9d2ddd9

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page