Skip to main content

servicewright

One Host, many Entrypoints — a batteries-optional microservice runtime for async Python.

PyPI Python License CI codecov Docs

Describe a service once as an AppSpec (DI container, lifecycle, observability, warmup, health) and run it through any number of pluggable entrypoints — HTTP, gRPC, scheduler, background daemon, one-shot batch — under one unified lifecycle. The "API vs worker" distinction does not exist at the core: a cron job and an HTTP request are the same thing — one unit of work in a fresh DI scope.

This is the model behind .NET Generic Host, Spring SmartLifecycle and go-kratos transport.Server, adapted to async Python.

Why

  • One lifecycle for every archetype: Bootstrap → Warmup → Ready → Serve → Drain → Cleanup. Kubernetes-correct shutdown out of the box: readiness flips to false before draining, every entrypoint finishes in-flight work within a grace window, the DI scope closes last, and a service that dies mid-serve exits non-zero instead of looking like a graceful stop.
  • DI-agnostic two-tier scopes: the core depends on no DI library. AppScope holds process-lifetime singletons; a fresh UnitScope wraps every request / RPC / job / message. A dishka adapter ships in the box; any container fits by implementing two methods.
  • Pluggable observability add-ons: metrics / tracing / logging / error-tracking are protocols in the kernel with selectable, extra-gated backends (prometheus, OpenTelemetry, Sentry, structlog). Adding a backend = one module + one register_sink call, zero core changes.
  • One error taxonomy, every transport: a ServiceError raised in business code renders as an RFC 9457 problem document over HTTP and as the mapped grpc.StatusCode over gRPC, with one masking rule for non-public details and a pluggable renderer when you own the wire format.
  • Zero hard dependencies: pip install servicewright brings pure Python. Every framework binding lives behind an extra; the kernel never imports an SDK, a vendor, or a transport.

Installation

pip install servicewright                    # pure kernel, zero dependencies
pip install "servicewright[fastapi]"         # + FastAPI/uvicorn entrypoint
pip install "servicewright[grpc]"            # + gRPC entrypoint
pip install "servicewright[apscheduler4]"    # + cron/scheduler entrypoint
pip install "servicewright[metrics,observability,sentry]"  # + prometheus, otel+structlog, sentry
pip install "servicewright[all]"             # everything except the conflicting [apscheduler3]

Requirements: Python 3.12+

Quick start — HTTP API + cron in ONE process

import asyncio

from servicewright import AppSpec, ObsConfig, ObservabilityManager, Service, run
from servicewright.adapters.apscheduler4 import ScheduledJob, SchedulerEntrypoint
from servicewright.adapters.fastapi import FastApiEntrypoint


def build_service() -> Service:
    spec = AppSpec(
        service_name="orders-service",
        create_container=build_container,   # your DI container factory
        observability=ObservabilityManager(
            ObsConfig(metrics="prometheus", tracing="otel", logging="structlog"),
        ),
    )

    http = FastApiEntrypoint(routers=(router,))          # kind="http"
    cron = SchedulerEntrypoint(jobs=[                    # kind="scheduler"
        ScheduledJob(id="sweep", func=sweep_expired_orders, trigger=interval_trigger),
    ])
    return Service(spec, entrypoints=[http, cron])


if __name__ == "__main__":
    asyncio.run(run(build_service(), Settings()))

Both entrypoints share one DI container, one observability setup and one graceful shutdown. Scaling the worker separately later = the same AppSpec in a second process with a different entrypoint list.

Entrypoints

Archetype Adapter Extra
HTTP API adapters.fastapi / adapters.litestar fastapi / litestar
gRPC API adapters.grpc grpc
Scheduled / cron adapters.apscheduler4 / adapters.apscheduler3 apscheduler4 / apscheduler3
Background daemon DaemonEntrypoint (built-in)
One-shot / batch OneShotEntrypoint (built-in)

Writing your own entrypoint = implementing four methods (bind, serve, drain, stop) with nothing installed.

What's inside

The kernel is core/; everything that touches a third-party SDK is an extra-gated adapter. An import-linter contract enforces the direction in CI: deleting adapters/ leaves core/ importable.

Module Responsibility Extra
servicewright AppSpec, Service, Host, run — the public vocabulary
core.contracts Entrypoint, Plugin, container/settings/health protocols
core.aio.host The lifecycle kernel: warmup → ready → serve → drain → cleanup
core.errors ServiceError, ErrorKind, RFC 9457 renderer + renderer seam
core.context Transport-neutral correlation store + outbound propagation
core.health HealthRegistry driving both HTTP routes and the gRPC health service
core.warmup Priority-grouped, fail-fast warmup before readiness flips
core.observability Sink protocols, NullObjects, backend registry, redaction
adapters.builtin DaemonEntrypoint, OneShotEntrypoint — zero-dependency
adapters.fastapi FastAPI entrypoint, middleware stack, problem-details handlers fastapi
adapters.litestar Litestar entrypoint litestar
adapters.grpc gRPC entrypoint over grpc-server-kit, error mapping, health bridge grpc
adapters.apscheduler4 / apscheduler3 Scheduler entrypoints with identical public surfaces apscheduler4 / apscheduler3
adapters.dishka dishka ⇄ core scope binding dishka
adapters.observability prometheus / OpenTelemetry / Sentry / structlog / stdlib sinks see below
adapters.warmers, adapters.health Redis / Postgres / Kafka warmers and checks redis, postgres, kafka
servicewright.testing FakeContainer, FakeEntrypoint, FakeScope, FakeSettings

Optional dependencies

Extra Pulls in Enables
fastapi fastapi, uvicorn, deadline-budget, prometheus-fastapi-instrumentator FastApiEntrypoint + its middleware stack
litestar litestar, uvicorn LitestarEntrypoint
grpc grpc-server-kit[reflection,channelz,health] GrpcEntrypoint, error mapping, health bridge
apscheduler4 / apscheduler3 apscheduler 4.x / 3.x SchedulerEntrypoint (one major per environment)
dishka dishka DishkaContainer
observability opentelemetry-sdk, OTLP gRPC exporter, structlog otel tracing + structlog logging sinks
fastapi-tracing the above + opentelemetry-instrumentation-fastapi HTTP request spans
metrics prometheus-client prometheus metrics sink + /system/metrics
sentry sentry-sdk sentry error-tracking sink
redis / postgres / kafka redis / sqlalchemy / aiokafka matching warmers and health checks
all everything except apscheduler3 the full runtime

Examples

Runnable, self-contained scripts (each exits 0):

Documentation

Full documentation at bedrock-python.github.io/servicewright. The reference architecture lives in ARCHITECTURE.md.

License

Apache 2.0 — see LICENSE.

Download files

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

Source Distribution

servicewright-0.1.0.tar.gz (101.4 kB view details)

Uploaded Source

Built Distribution

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

servicewright-0.1.0-py3-none-any.whl (155.2 kB view details)

Uploaded Python 3

File details

Details for the file servicewright-0.1.0.tar.gz.

File metadata

  • Download URL: servicewright-0.1.0.tar.gz
  • Upload date:
  • Size: 101.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.12.3 {"installer":{"name":"uv","version":"0.12.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for servicewright-0.1.0.tar.gz
Algorithm Hash digest
SHA256 61e2b6ebd93538c9e44504e0af233cc702cbe4a0615199836af04de1829bb1ed
MD5 ccef2a7abb8d61795901ab101ce1c4a5
BLAKE2b-256 8e4ac10af427a8b19e05001bdc0efee68416eac443353c4dfaeb62b83d4b42fd

See more details on using hashes here.

File details

Details for the file servicewright-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: servicewright-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 155.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: uv/0.12.3 {"installer":{"name":"uv","version":"0.12.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

File hashes

Hashes for servicewright-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e914be67567738e203ec3b92ed9c8bc465783a6879d881c1b0f84d7fa2d1e316
MD5 73e46f278f37d01484f4e62b68ca64ea
BLAKE2b-256 6b484776841ab44f4904aa60b2fd6025fdea3d5ace69e6b7a17da8a7e715e372

See more details on using hashes here.

Release history Release notifications | RSS feed

0.4.0

2 files

0.3.0

2 files

0.2.0

2 files

This release

0.1.0 This release

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page