Skip to content

Defining services and types

This is the Python reference for service decorators and payload definitions. Use it when extending a working service, for example adding a task-list stream to a task creator. For a walkthrough of the four call patterns in Python and TypeScript, start with Define a service.

Install and run the Python first service before using these fragments. A definition describes the wire interface; the server registers handlers and the client owns the connection. Names such as WatchRequest in individual examples are application-defined payloads.

@service marks a class as an Aster RPC service. It scans the class for methods decorated with @rpc, @server_stream, @client_stream, or @bidi_stream, extracts their type signatures, and attaches a ServiceInfo metadata object to the class.

Three calling forms are supported:

from aster import service
# Bare -- service name defaults to the class name ("Greeter").
@service
class Greeter:
...
# Explicit name.
@service("AgentControl")
class AgentControlService:
...
# Keyword arguments -- name still defaults to the class name.
@service(version=2, scoped="session")
class ChatSession:
def __init__(self, peer: str):
self.peer = peer
...
Parameter Type Default Description
name (positional) str Class name The service name used on the wire and in service discovery.
version int 1 Service version. Consumers specify which version they want.
serialization SerializationMode or list[SerializationMode] [XLANG] Which serialization modes this service supports.
scoped str "shared" "shared" (one instance serves all connections) or "session" (an instance is keyed by connection, session ID, and service; Python __init__ must accept peer).
interceptors list[type] [] Interceptor classes applied to every method in the service.
max_concurrent_streams int or None None Accepted as metadata; the Python dispatcher does not enforce this setting. Configure and test actual transport/application resource limits separately.

@rpc marks a method as a unary RPC (one request in, one response out). It is the most common pattern.

from aster import service, rpc
@service
class Calculator:
# Bare -- no options.
@rpc
async def add(self, req: AddRequest) -> AddResponse:
return AddResponse(result=req.a + req.b)
# With options.
@rpc(timeout=10.0, idempotent=True)
async def multiply(self, req: MulRequest) -> MulResponse:
return MulResponse(result=req.a * req.b)
Parameter Type Default Description
timeout float or None None Default timeout in seconds. Consumers can override per-call.
idempotent bool False Marks the method as safe to retry. Used by the retry interceptor.
serialization SerializationMode or None None Override the service-level serialization mode for this method.

All @rpc methods must be async def coroutines. They receive a single request argument (after self) and return a single response.

Aster supports three streaming patterns beyond unary.

The server sends multiple responses for one request. The method must be an async generator (use yield).

from typing import AsyncIterator
from aster import service, server_stream
@service
class Ticker:
@server_stream
async def watch(self, req: WatchRequest) -> AsyncIterator[PriceUpdate]:
while True:
price = await get_latest_price(req.symbol)
yield PriceUpdate(symbol=req.symbol, price=price)
await asyncio.sleep(1.0)

Consumers iterate over the result:

async for update in ticker.watch(WatchRequest(symbol="AAPL")):
print(update.price)

The client sends multiple requests; the server returns one response. The method receives an AsyncIterator of requests.

from typing import AsyncIterator
from aster import service, client_stream
@service
class Aggregator:
@client_stream
async def sum(self, reqs: AsyncIterator[NumberRequest]) -> SumResponse:
total = 0
async for req in reqs:
total += req.value
return SumResponse(total=total)

Both sides stream concurrently. The method is an async generator that receives an AsyncIterator of requests and yields responses.

from typing import AsyncIterator
from aster import service, bidi_stream
@service
class Chat:
@bidi_stream
async def converse(
self, messages: AsyncIterator[ChatMessage]
) -> AsyncIterator[ChatMessage]:
async for msg in messages:
yield ChatMessage(text=f"echo: {msg.text}")

All three streaming decorators accept timeout and serialization keyword arguments, same as @rpc. @client_stream also accepts idempotent.

Request and response types are plain Python dataclasses. No base class or schema definition is required.

from dataclasses import dataclass
@dataclass
class AddRequest:
a: int = 0
b: int = 0
@dataclass
class AddResponse:
result: int = 0

Dataclasses can contain other dataclasses. The type graph is walked automatically.

from dataclasses import dataclass, field
@dataclass
class Address:
street: str = ""
city: str = ""
zip_code: str = ""
@dataclass
class Person:
name: str = ""
age: int = 0
address: Address = field(default_factory=Address)

The Python codec supports these common field shapes. Cross-language compatibility also depends on the peer binding and its schema mapping; this list does not qualify every combination:

  • Primitives: int, float, str, bool, bytes, bytearray
  • Collections: list[T], dict[K, V], set[T]
  • Optional: T | None or Optional[T]
  • Nested dataclasses
  • Enums: any enum.Enum subclass (including IntEnum and StrEnum)

All fields should have default values so that deserialization can construct partial objects.

When Aster serializes a dataclass across the wire, it needs a string tag to identify the type. By default, the @service decorator auto-derives this tag from the Python module and class name (e.g., hello_service.HelloRequest). This is fine for development, but it breaks if you rename or move the module.

For production services, use @wire_type to declare an explicit, stable tag:

from dataclasses import dataclass
from aster import wire_type
@wire_type("hello/HelloRequest")
@dataclass
class HelloRequest:
name: str = ""
@wire_type("hello/HelloResponse")
@dataclass
class HelloResponse:
message: str = ""

The tag string is split on the last / into a namespace and type name. If there is no /, the namespace is empty. The tag must be unique across all types in your system.

When you use auto-derived tags (no @wire_type), the @service decorator emits a warning:

UserWarning: Type HelloRequest auto-tagged as 'hello_service.HelloRequest';
use @wire_type for stable wire identity

This is harmless during development but serves as a reminder to add explicit tags before deploying to production.

  • Development / prototyping: skip it. Auto-derivation works fine.
  • Production / multi-service systems: use it. Wire tags are part of the serialization contract. If a consumer and producer disagree on the tag for a type, deserialization will fail.
  • Cross-language interop: required. The Fory XLANG serializer uses these tags to match types across languages.

A contract ID is a deterministic BLAKE3 hash of the canonical interface descriptor. It covers service and method settings as well as the reachable payload type graph, rather than the handler implementation. Matching the name and version alone is insufficient. See contract identity for the full hash inputs and change rules.

The contract ID is computed automatically. You do not need to set it. contract_id_from_service returns it for any @service-decorated class:

from aster.contract.identity import contract_id_from_service
@service
class Calculator:
@rpc
async def add(self, req: AddRequest) -> AddResponse: ...
cid = contract_id_from_service(Calculator)
print(cid) # e.g. "a1b2c3d4..."

If you change a method signature, add a method, or change the serialization mode, the contract ID changes. Compare the new descriptor with existing callers before rollout; a changed ID requires an explicit compatibility decision.

Aster exposes XLANG plus Python-only NATIVE and ROW modes:

Mode Enum value Description
XLANG SerializationMode.XLANG Cross-language mode via Apache Fory. Types are registered with string tags (via @wire_type or auto-derivation). Works across Python, TypeScript, Java, Go, Rust, etc. This is the default.
NATIVE SerializationMode.NATIVE Language-native Fory serialization. Python-only; validate its behavior for your types before using it. No @wire_type tags needed.

The default, XLANG, supports Python-to-Python and cross-language calls. Dynamic proxies synthesize XLANG types from the published manifest. JSON wire mode has been retired. ROW also exists for Python; see the ROW example for its limits.

To change the mode:

from aster import service, rpc, SerializationMode
# All methods in this service use NATIVE serialization.
@service(serialization=SerializationMode.NATIVE)
class FastService:
...
# Override for a single method.
@service
class MixedService:
@rpc(serialization=SerializationMode.NATIVE)
async def fast_path(self, req: Req) -> Resp:
...
@rpc
async def normal_path(self, req: Req) -> Resp:
...

Here is a complete service definition with explicit wire types, a server stream, and a unary method:

import asyncio
from dataclasses import dataclass
from typing import AsyncIterator
from aster import service, rpc, server_stream, wire_type
@wire_type("todo/Task")
@dataclass
class Task:
id: str = ""
title: str = ""
done: bool = False
@wire_type("todo/CreateTaskRequest")
@dataclass
class CreateTaskRequest:
title: str = ""
@wire_type("todo/ListTasksRequest")
@dataclass
class ListTasksRequest:
pass
@service("TodoService", version=1)
class TodoService:
def __init__(self):
self._tasks: dict[str, Task] = {}
self._counter = 0
@rpc(idempotent=False)
async def create_task(self, req: CreateTaskRequest) -> Task:
self._counter += 1
task = Task(id=str(self._counter), title=req.title, done=False)
self._tasks[task.id] = task
return task
@server_stream
async def list_tasks(self, req: ListTasksRequest) -> AsyncIterator[Task]:
for task in self._tasks.values():
yield task

With the Todo service registered, call create_task once, then consume list_tasks. Expect the created ID and title to appear in the stream. A second creation produces a different ID, so retrying a timed-out creation can create a duplicate; keep it non-idempotent or add application deduplication. This example stores tasks in memory and loses them on restart.

Next, register the Python server and call it.