We are going to design a hybrid RPC+event system with the following features:
- Idempotency: Ensure that duplicate requests do not cause duplicate effects.
- Retries: Automatic retries for failed RPC calls with exponential backoff.
- Tracing: Distributed tracing for debugging and monitoring.
- Backpressure: Handle high load by applying backpressure on the event producer.
We assume we are in a distributed system with multiple services.
Components:
- Client: The service that initiates RPC calls and produces events.
- Server: The service that handles RPC calls and emits events.
We'll design a contract (interface) for the client and server that includes:
For RPC:
- The client will have a method to make an RPC call with idempotency key, retry policy, and tracing context.
- The server will have an endpoint that can handle the RPC and use the idempotency key to avoid duplicate processing.
For Events:
- The client will have a method to produce an event (publish) that can be subjected to backpressure.
- The server will have a way to subscribe to events and process them.
We'll define:
-
Idempotency:
- The client must generate an idempotency key for each request (or for a set of requests that should be idempotent).
- The server must store the idempotency key for processed requests and return the same response for duplicate requests.
-
Retries:
- The client will retry on certain errors (like network errors, server 5xx) with exponential backoff.
- We'll define a retry policy (max retries, backoff strategy).
-
Tracing:
- We'll use a trace context (like a trace ID) that is passed along in the RPC and event headers.
- The server will propagate the trace context to any downstream calls or events.
-
Backpressure:
- The event producer (client) will check if the event broker (or the server) is under heavy load and apply backpressure by slowing down or buffering.
However, note that backpressure is typically a concern between the event producer and the message broker. We can implement:
- The client, when producing events, can check the broker's load (if exposed) and adjust the rate.
- Alternatively, the broker can provide a way to tell the producer to slow down (e.g., via a control message or by having the producer monitor its own queue length).
Since we are designing a contract, we can define:
- The event producer (client) should have a way to know the current load (maybe via an admin endpoint on the broker) and then adjust its production rate.
- Or, we can have the broker send a "slow down" signal (but that would require the broker to have a way to communicate with the producer).
Given the complexity, let's focus on the RPC part with idempotency, retries, and tracing, and for events we'll define a method that can be subject to backpressure by having the client check a metric or status.
Alternatively, we can design:
For RPC:
- Client: rpcCall(request, idempotencyKey, retryPolicy, traceContext)
- Server: handleRpc(request, idempotencyKey, traceContext)
For Events:
- Client: produceEvent(event, traceContext) which may block or throw if backpressure is applied.
- Server: handleEvent(event, traceContext)
But note: backpressure in event systems is often implemented by having the producer check the broker's queue depth or by having flow control.
Since we are designing a contract, we can define:
The client must implement a canProduce check (non-blocking) that returns true if the broker is ready to accept more events.
However, in practice, we might use a library that handles this (like a reactive stream with backpressure).
Given the complexity and the fact that we are only defining a contract, we can leave the backpressure mechanism to the implementation but require the client to have a way to be notified of backpressure (e.g., exception when broker is full).
Let's define:
Event production may throw a BackpressureException if the broker is under heavy load and cannot accept more events at the moment.
The client must catch this and either buffer or slow down.
Alternatively, we can define:
The client must have a configuration for max in-flight events and must not exceed that.
But again, that's implementation.
Let's try to define a simple contract in an interface-like style (in a language-agnostic way).
We'll define two main interfaces: HybridClient and HybridServer.
However, note that the same service can be both client and server. So we might have:
Service A (client) calls Service B (server) via RPC.
Service B (server) produces events that Service A (client) might consume? Or other services?
Actually, the event system is typically asynchronous and decoupled. So:
- The client (any service) can produce events to an event broker.
- The server (any service) can subscribe to events from the broker.
So we have:
Client interface (for a service that produces events and makes RPC calls):
- `rpcCall(request, idempotencyKey, retryPolicy, traceContext)`
- `produceEvent(event, traceContext)` // may throw BackpressureException
Server interface (for a service that handles RPC and consumes events):
- `rpcHandler(request, idempotencyKey, traceContext)`
- `eventHandler(event, traceContext)`
But note: the same service can have both.
We'll also need to define:
-
The structure of retryPolicy: max retries, backoff function (or parameters like initial interval, multiplier, max interval).
-
The traceContext could be a map of trace-related headers (like trace ID, span ID, etc.)
-
The idempotencyKey is a unique string for the request that the server can use to deduplicate.
-
The request and event are generic payloads. We can define them as binary or structured (like JSON).
However, to make it concrete, let's assume we are using a protocol like HTTP/REST or gRPC.
But since we are designing a contract, we can be abstract.
Let's define:
Data structures:
IdempotencyKey: string
RetryPolicy:
maxRetries: integer
initialBackoff: duration
maxBackoff: duration
multiplier: float
TraceContext:
traceId: string
spanId: string
[other fields as needed]
Request:
body: bytes
headers: map<string, string> // including the idempotencyKey and traceContext as headers? Or as separate fields?
Event:
body: bytes
headers: map<string, string> // including traceContext
But note: in RPC, we might have a more structured request (with method, parameters). Let's assume:
RPCRequest:
method: string
parameters: bytes (could be JSON, protobuf, etc.)
idempotencyKey: string // separate from headers? Or in headers?
traceContext: TraceContext
However, in HTTP we often put these in headers. But for our contract, we can define:
The RPC call must include:
- method
- parameters (or a structured request object)
- idempotencyKey (as a header or in the body? We'll leave it to the transport)
- traceContext (again, as headers or in the body)
Similarly for events.
To keep it simple, let's assume we are using a message broker that supports headers.
So:
For RPC: we send a message with:
routing key: the method name
body: the parameters
headers:
idempotency-key: <key>
trace-id: <traceId>
span-id: <spanId>
For events: we send a message with:
routing key: the event type
body: the event data
headers:
trace-id: <traceId>
span-id: <spanId>
Now, the server:
When handling an RPC:
- It must check the idempotency-key. If it has already processed a request with that key, it must return the same response (without re-executing).
- It must propagate the trace context (create a new span for the processing and set the traceId and spanId in the response headers?).
When handling an event:
- It must use the trace context for logging and if it makes further RPC calls or produces events, it should propagate the same traceId (and generate a new spanId for the new operation).
For the client:
When making an RPC:
- It must generate an idempotencyKey for the request (if not provided? Or we require it? We'll require it to be provided by the caller).
- It must generate a traceId if one is not provided (or use the current trace context).
- It must attach the idempotencyKey and traceContext to the request.
- It must implement retry logic: on certain errors (network, 5xx) it will retry with the same idempotencyKey and traceContext.
When producing an event:
- It must attach the traceContext.
- It must handle backpressure: if the broker is full, it may throw a BackpressureException.
We also need to consider:
- How does the server store idempotency keys? It must be persistent (at least until the response is cached) and have a TTL? We don't specify that in the contract, but the server must ensure that duplicates are detected for a reasonable time.
Let's write the contracts:
We'll define two interfaces:
Interface for a service that can make RPC calls and produce events (Client):
class HybridClient {
// RPC call with idempotency, retries, and tracing.
// Returns the response or throws an exception after retries are exhausted.
rpcCall(method: string, parameters: bytes, idempotencyKey: string, traceContext: TraceContext, retryPolicy: RetryPolicy): bytes
// Produce an event. May throw BackpressureException.
produceEvent(eventType: string, eventData: bytes, traceContext: TraceContext): void
}
Interface for a service that can handle RPC calls and events (Server):
class HybridServer {
// Handles an RPC call. The server must use the idempotencyKey to deduplicate.
// The server must propagate the traceContext (by creating a new span and setting the spanId in the response?).
// The server must return the response for the given method and parameters.
handleRpc(method: string, parameters: bytes, idempotencyKey: string, traceContext: TraceContext): bytes
// Handles an event.
handleEvent(eventType: string, eventData: bytes, traceContext: TraceContext): void
}
But note: the server might be implemented as a set of endpoints. We are abstracting that.
However, in practice, the server might be a web server that receives HTTP requests. Then:
The `handleRpc` would be mapped to an HTTP endpoint that expects:
- Method in the URL or header.
- Parameters in the body.
- idempotencyKey in a header.
- traceContext in headers.
Similarly, for events, the server might be consuming from a message broker.
We have not defined:
- How the client gets the traceContext? Typically, the traceContext is part of the current context (like in a web request, it comes from incoming headers). For the initial client call, it might generate a new trace.
- The retry policy: the client must implement the retry logic with exponential backoff. We defined the policy as part of the rpcCall parameters.
We also need to define the BackpressureException.
Let's define:
class BackpressureException extends Exception {
// may include information about current load, etc.
}
And for the server's idempotency store:
We don't define it in the contract, but the server must have a way to store and lookup idempotency keys. This could be a distributed cache (like Redis) or a database.
Additional note:
The server, when processing an RPC, might produce events. In that case, it should use the same traceContext (with a new spanId) when producing events.
Similarly, the server, when handling an event, might make an RPC call (as a client). Then it should use the traceContext from the event (and generate a new spanId for the RPC call).
So the traceContext is propagated along the entire call chain.
Let's adjust:
In the server's `handleRpc`:
- It receives a traceContext (with traceId and spanId). It should create a new span for the RPC processing (child of the received span) and set the current span to that new one.
- Then, if it makes an RPC call (to another service) or produces an event, it passes the same traceId but a new spanId (the current span's spanId) and then creates a new span for the outbound call.
This is standard distributed tracing.
We have not defined how the traceContext is serialized. Typically, it's done via headers (like B3 or W3C trace context).
We'll leave the serialization format out of the contract.
Summary:
We have defined:
- RPC call with idempotency key, retry policy, and trace context.
- Event production with trace context and backpressure.
- Server-side handling of RPC (with idempotency) and events.
This is a high-level contract. Implementation details (like how to store idempotency keys, how to do retries, how to propagate trace context) are left to the implementers.
However, we must specify:
- The idempotency key must be unique for each logical request that should be idempotent.
- The server must return the same response for the same idempotency key, even if the request is retried.
And for backpressure:
- The client's `produceEvent` must fail (throw BackpressureException) if the broker cannot accept the event at the moment.
This contract is transport-agnostic. We can implement it over HTTP, gRPC, or a message broker.
Let's write the interfaces in a more formal way (pseudo-code):
We'll define:
struct TraceContext {
string traceId;
string spanId;
// ... other fields as needed
}
struct RetryPolicy {
int maxRetries;
duration initialBackoff;
duration maxBackoff;
float multiplier;
}
exception BackpressureException {}
interface HybridClient {
bytes rpcCall(string method, bytes parameters, string idempotencyKey, TraceContext traceContext, RetryPolicy retryPolicy) throws RpcException, BackpressureException;
void produceEvent(string eventType, bytes eventData, TraceContext traceContext) throws BackpressureException;
}
interface HybridServer {
bytes handleRpc(string method, bytes parameters, string idempotencyKey, TraceContext traceContext) throws RpcException;
void handleEvent(string eventType, bytes eventData, TraceContext traceContext);
}
Note: The rpcCall might throw RpcException (for non-retryable errors or after retries exhausted) and BackpressureException (if we consider that producing an event is part of the RPC?).
Actually, in our design, produceEvent is separate. But note: the RPC call might produce events as a side effect. Then the backpressure in event production might be part of the RPC processing?
We have two separate concerns:
- The RPC call itself might have backpressure (if the server is overloaded, it might reject with 429 or 503). But that's a different kind of backpressure (on the RPC endpoint).
- The event production (which might be inside the RPC) might have backpressure.
We are only defining backpressure for the event production by the client. The server's RPC endpoint might have its own backpressure (like rate limiting) but that's not part of this contract.
So, the client's rpcCall does not throw BackpressureException because that's for event production. The server's RPC endpoint might return an error (like 429) and then the client will retry (if it's a retryable error) or fail.
We must define which errors are retryable. Typically:
- Network errors (timeout, connection refused) are retryable.
- 5xx errors are retryable.
- 4xx errors (except 429) are not retryable? But 429 (Too Many Requests) might be retryable after a delay.
We can let the retry policy decide based on the status code? But we didn't specify the transport.
Alternatively, we can define:
The client should retry on:
- Any exception that indicates a transient failure (like network timeout, server 5xx, 429).
But in our contract, we are not specifying the transport, so we cannot rely on HTTP status codes.
We can change the rpcCall to return a RpcResponse that includes a status and the body, and then the client decides based on the status?
However, in many RPC frameworks, the exception is thrown for non-2xx responses.
We can define:
The client's `rpcCall` will throw an `RpcException` for any non-success response. The `RpcException` should include a status code (or error type) that the client can use to decide if it's retryable.
But we are not defining the wire format.
Let's adjust:
We define:
class RpcException extends Exception {
int statusCode; // or an error enum
string message;
}
And the client will retry if the statusCode is in a set of retryable statuses (which we can define as part of the retry policy?).
Alternatively, we can have the retry policy include a predicate that decides if an exception is retryable.
Since we are designing a contract, we can say:
The client must retry on exceptions that are considered transient. The set of transient exceptions is implementation-specific, but must at least include network errors and server errors (5xx).
However, to be more precise, we can define:
The client's retry policy includes a function `isRetryable(exception)`.
But that might be too implementation-specific.
Let's stick to:
The client must retry on:
- Any exception that is a subclass of `TransientException` (which we define) and also on 5xx and 429 status codes (if the transport uses HTTP).
But again, we are transport-agnostic.
Given the complexity, we might leave the retry condition as part of the retry policy:
RetryPolicy {
...
predicate<Exception> shouldRetry;
}
Then the client uses that predicate to decide.
So, we adjust:
struct RetryPolicy {
int maxRetries;
duration initialBackoff;
duration maxBackoff;
float multiplier;
predicate<Exception> shouldRetry;
}
Now, the client will:
attempt = 0
while (attempt <= maxRetries) {
try {
return makeRpcCall(...);
} catch (Exception e) {
if (!shouldRetry(e) || attempt == maxRetries) {
throw e;
}
wait(backoff(attempt));
attempt++;
}
}
This is more flexible.
Final note:
We have not defined the exact mechanism for the server to store idempotency keys. The server must have a persistent store (like a database) that maps idempotencyKey to the response. The server must also clean up old keys (with TTL). This is an implementation detail.
Also, the server must be careful that the idempotencyKey is unique per request that should be idempotent. The client must generate a unique key for each new request, but for retries, it must use the same key.
So, the client must generate the idempotencyKey once and then reuse it for retries.
In the contract, we require the client to provide the idempotencyKey for each RPC call. The client must generate it (if not provided by the caller) and then use the same for retries.
We can adjust the client interface to not require the idempotencyKey in every call if we can store it in the client? But the client might be stateless. So we require the caller to provide it.
Alternatively, we can have:
rpcCall(method, parameters, retryPolicy, traceContext) // and the client generates an idempotencyKey internally and returns it? But then how does the caller know?
We want the caller to be able to provide the idempotencyKey so that they can control it (for example, if they are retrying the same logical operation, they can use the same key).
So we keep it as a required parameter.
This is our hybrid RPC+event integration contract.
Let's write it in a more structured way:
We'll define the following types:
TraceContext: { traceId: string, spanId: string, ... }
RetryPolicy: {
maxRetries: number,
initialBackoff: number (milliseconds),
maxBackoff: number (milliseconds),
multiplier: number,
shouldRetry: (error: any) => boolean
}
RpcException: { statusCode: number, message: string }
BackpressureException: {}
Interfaces:
HybridClient:
rpcCall(method: string, parameters: any, idempotencyKey: string, traceContext: TraceContext, retryPolicy: RetryPolicy): any
produceEvent(eventType: string, eventData: any, traceContext: TraceContext): void
HybridServer:
handleRpc(method: string, parameters: any, idempotencyKey: string, traceContext: TraceContext): any
handleEvent(eventType: string, eventData: any, traceContext: TraceContext): void
Note: We use any for parameters and eventData to be language-agnostic. In practice, they would be serialized (e.g., JSON, protobuf).
We assume that the transport (HTTP, gRPC, etc.) will serialize these.
This is a high-level contract. The actual implementation will depend on the chosen transport and frameworks.
Example of how it might be used:
Client:
Let's say we have a method to create a user.
We generate an idempotencyKey for this user creation (maybe based on user email and operation, or a UUID if we don't have a natural key).
We create a traceContext (maybe from the current request, or generate a new trace).
We call:
client.rpcCall(
"createUser",
{ "email": "user@example.com", "name": "John" },
"idempotency-key-123",
{ traceId: "trace-123", spanId: "span-456" },
{ maxRetries: 3, initialBackoff: 100, maxBackoff: 1000, multiplier: 2, shouldRetry: (e) => e instanceof NetworkError || (e instanceof RpcException && (e.statusCode >= 500 || e.statusCode == 429)) }
)
If the RPC fails with a retryable error, it will retry up to 3 times with exponential backoff.
If the RPC succeeds, then the server will have stored the idempotencyKey and the response. If we call again with the same key, the server will return the same response without re-executing.
Event production:
After the user is created, we might produce an event:
client.produceEvent(
"user.created",
{ "userId": 123, "email": "user@example.com" },
{ traceId: "trace-123", spanId: "span-789" } // note: we might create a new span for the event production?
)
But note: the traceContext we use for the event should be the same trace (traceId) but a new span (for the event production). So the client, when producing the event, should generate a new spanId and set the traceId from the current context.
We didn't specify that in the contract, but the client must manage the span hierarchy. Typically, the client would have a tracer that creates a new span for the event production and then uses that span's context (which has the same traceId but new spanId) when calling `produceEvent`.
So, the client's produceEvent should be called with the current span's context (which is a new span if we are in a new operation).
Similarly, the server, when handling an RPC, might produce events. It should use the traceContext from the RPC (with a new span for the event production) and then call produceEvent with that new context.
This contract does not specify how the traceContext is created and propagated, but it must be done.
We have now defined:
- RPC with idempotency, retries, and tracing.
- Event production with tracing and backpressure.
This should meet the requirements.
However, note that the server's handleRpc might also produce events. In that case, the server (as a client) would use its own HybridClient to produce events. So the server must have a HybridClient instance.
Similarly, the server might make RPC calls to other services.
So, the server implementation will have:
class MyService implements HybridServer {
private HybridClient client; // to make RPC calls and produce events
public bytes handleRpc(String method, bytes parameters, String idempotencyKey, TraceContext traceContext) {
// ... process ...
// if we need to produce an event:
TraceContext eventTraceContext = tracer.newChild(traceContext); // create a new span
client.produceEvent("some.event", eventData, eventTraceContext);
}
public void handleEvent(String eventType, bytes eventData, TraceContext traceContext) {
// ... process ...
}
}
And the client that calls handleRpc is also a HybridClient.
This way, we have a uniform way for any service to make RPC calls and produce events.
We have not defined:
- How the server's `handleRpc` is exposed? That's transport-specific.
But that's okay because the contract is about the interface that the service implements, not how it's exposed.
This is a design for a hybrid RPC+event system with the required features.
We can now write the contract in a more formal way (like an interface in Java or TypeScript) but since the question is language-agnostic, we'll leave it as pseudo-code.
Let me summarize the key points:
- Idempotency: via idempotencyKey in RPC calls, server stores and returns same response for same key.
- Retries: client-side with exponential backoff, configurable retry policy (including which errors are retryable).
- Tracing: via TraceContext (traceId and spanId) passed in every RPC and event, and servers/clients must propagate (create child spans) for each new operation.
- Backpressure: client's produceEvent throws BackpressureException when broker is overloaded.
This should cover the requirements.
However, note that backpressure might also be needed for RPCs? But typically, RPCs are request-response and the client can apply backpressure by not sending more requests (or by using a semaphore). But that's client-side and not part of the contract.
The contract only specifies backpressure for event production because that's where the broker might be overwhelmed.
For RPCs, the server can reject with 429 and the client can retry (with backoff) or the client can implement its own rate limiting.
So we are good.
Let me write the final contract in a structured way:
Types:
TraceContext:
traceId: string
spanId: string
[optional: sampled, debug, etc.]
RetryPolicy:
maxRetries: integer
initialBackoff: integer (milliseconds)
maxBackoff: integer (milliseconds)
multiplier: number
shouldRetry: function (error) -> boolean
RpcException:
statusCode: integer
message: string
BackpressureException: {}
Interfaces:
HybridClient:
rpcCall(method: string, parameters: any, idempotencyKey: string, traceContext: TraceContext, retryPolicy: RetryPolicy): any throws RpcException, BackpressureException
produceEvent(eventType: string, eventData: any, traceContext: TraceContext): void throws BackpressureException
HybridServer:
handleRpc(method: string, parameters: any, idempotencyKey: string, traceContext: TraceContext): any throws RpcException
handleEvent(eventType: string, eventData: any, traceContext: TraceContext): void
Notes:
- The `rpcCall` method must use the same `idempotencyKey` for all retries of the same logical request.
- The server's `handleRpc` must store the `idempotencyKey` and the response (or an error) and return the same response for the same key within a certain time window (idempotency window).
- The `produceEvent` method must propagate the `traceContext` (with a new span if it's a new operation) and must fail with `BackpressureException` if the event broker cannot accept the event at the moment.
- The `handleEvent` method must use the `traceContext` for logging and if it makes RPC calls or produces events, it must create a new span (child of the given span) and use that new context.
This is the contract.
However, note that the HybridClient and HybridServer are separate interfaces. In practice, a service that both calls RPCs and handles RPCs will implement HybridServer and also have a HybridClient instance for making outbound calls.
We have not defined:
- How the server's `handleRpc` is mapped to an actual endpoint? That's up to the framework.
But the contract for the service implementation is clear.
We can now stop here.
If we were to implement this, we would need to choose a transport and a tracing library, and an idempotency store.
But the question only asks for the contract.
We have provided a contract that includes:
- Idempotency (via idempotencyKey in RPCs)
- Retries (via RetryPolicy in RPCs)
- Tracing (via TraceContext in both RPCs and events)
- Backpressure (via BackpressureException in event production)
This meets the requirements.
I'll design a comprehensive hybrid RPC+event integration contract with all the requested features. This is a language-agnostic contract specification suitable for distributed systems.
Hybrid RPC+Event Integration Contract
1. Core Interfaces
// Common tracing context
message TraceContext {
string trace_id = 1; // W3C Trace Context or equivalent
string span_id = 2; // Current span ID
string parent_span_id = 3; // Parent span if any
bool sampled = 4; // Sampling decision
map<string, string> baggage = 5; // propagated key-values
}
// Idempotency key structure
message IdempotencyKey {
string key = 1; // Unique idempotency key
string scope = 2; // Namespace/scope (tenant, user, etc.)
int64 ttl_seconds = 3; // Key expiration time
}
// Retry policy configuration
message RetryPolicy {
int32 max_attempts = 1; // Max retry attempts (excluding initial)
double initial_interval_ms = 2; // Initial backoff (ms)
double max_interval_ms = 3; // Max backoff cap (ms)
double multiplier = 4; // Backoff multiplier (e.g., 2.0 for exponential)
enum RetryOn {
TRANSIENT_ERROR = 0;
SERVER_ERROR = 1;
ALL = 2;
NONE = 3;
}
RetryOn retry_on = 5;
double jitter_factor = 6; // Randomization factor (0.0-1.0)
}
// Backpressure signals
message BackpressureSignal {
enum Level {
NORMAL = 0;
ELEVATED = 1; // Producer should slow down
CRITICAL = 2; // Producer should stop/shed load
}
Level level = 1;
int32 current_queue_depth = 2;
int32 recommended_delay_ms = 3;
string reason = 4; // e.g., "memory_pressure", "cpu_saturation"
}
2. RPC Interface with Guarantees
// RPC Request with all metadata
message HybridRpcRequest {
string method = 1; // RPC method name
bytes payload = 2; // Serialized request body
IdempotencyKey idempotency = 3; // Idempotency guarantee
TraceContext trace = 4; // Distributed tracing
RetryPolicy retry_policy = 5; // Client-side retry config
int64 deadline_ms = 6; // Client deadline
map<string, string> metadata = 7; // Additional headers
}
// RPC Response with metadata
message HybridRpcResponse {
oneof result {
bytes success = 1; // Successful response
Error error = 2; // Error response
}
TraceContext trace = 3; // Updated trace context
bool idempotent_replay = 4; // True if served from cache
int64 server_processing_time_ms = 5; // Server-side timing
map<string, string> metadata = 6; // Response headers
}
// Error structure
message Error {
int32 code = 1; // Application-specific error code
string message = 2; // Human-readable error
enum Type {
CLIENT = 0; // Client error (don't retry)
SERVER = 1; // Server error (retry possible)
BACKPRESSURE = 2; // System backpressure
IDEMPOTENCY = 3; // Idempotency conflict/error
}
Type type = 3;
string retry_after_ms = 4; // Recommended retry delay
map<string, string> details = 5; // Error-specific details
}
// Service definition
service HybridRpcService {
// Synchronous RPC with full metadata
rpc Invoke(HybridRpcRequest) returns (HybridRpcResponse);
// Bidirectional streaming for complex scenarios
rpc Stream(stream HybridRpcRequest) returns (stream HybridRpcResponse);
}
3. Event Interface with Backpressure
// Event message
message HybridEvent {
string event_type = 1; // Event name/type
string source_service = 2; // Publishing service
bytes payload = 3; // Event data
TraceContext trace = 4; // Tracing context
int64 timestamp = 5; // Event creation time
string idempotency_key = 6; // Optional idempotency for events
map<string, string> headers = 7; // Event headers
}
// Event producer interface
service HybridEventProducer {
// Produce event with backpressure awareness
// Returns immediately if accepted, throws if backpressure critical
rpc Produce(HybridEvent) returns (ProduceResponse);
// Batch production with flow control
rpc ProduceBatch(stream HybridEvent) returns (BatchResult);
// Query current backpressure status
rpc GetBackpressureStatus(Empty) returns (BackpressureStatus);
}
// Response for produce operations
message ProduceResponse {
bool accepted = 1; // Event accepted by broker
string event_id = 2; // Broker-assigned ID (if accepted)
BackpressureSignal signal = 3; // Current backpressure level
int64 queued_at_ms = 4; // Queue timestamp
}
// Batch production result
message BatchResult {
repeated string accepted_event_ids = 1;
repeated string rejected_event_ids = 2;
BackpressureSignal final_signal = 3;
int32 successes = 4;
int32 failures = 5;
}
// Backpressure status query
message BackpressureStatus {
BackpressureSignal signal = 1;
int32 queue_depth = 2;
int32 consumer_lag = 3;
double memory_usage_percent = 4;
double cpu_usage_percent = 5;
int64 oldest_unprocessed_event_age_ms = 6;
}
4. Server-Side Implementation Requirements
// Server configuration
message ServerConfig {
// Idempotency store configuration
IdempotencyConfig idempotency = 1;
// Tracing configuration
TracingConfig tracing = 2;
// Backpressure thresholds
BackpressureConfig backpressure = 3;
// Retry configuration (for server-side retries if needed)
RetryPolicy server_retry_policy = 4;
}
message IdempotencyConfig {
StorageType storage = 1; // MEMORY, REDIS, DATABASE
int64 ttl_seconds = 2; // Default TTL
int64 max_keys = 3; // Max keys to store
bool enabled = 4; // Enable/disable
}
message TracingConfig {
bool enabled = 1;
string sampling_rate = 2; // e.g., "0.1" for 10%
string exporter_endpoint = 3; // Jaeger/Zipkin endpoint
bool record_headers = 4; // Propagate all headers
}
message BackpressureConfig {
int32 queue_size_threshold = 1; // Events in queue threshold
int32 memory_threshold_mb = 2; // Memory usage threshold
int32 cpu_threshold_percent = 3; // CPU usage threshold
int32 consumer_lag_threshold = 4; // Max consumer lag events
int32 cool_down_ms = 5; // Min time between signal updates
}
5. Client-Side Implementation Requirements
message ClientConfig {
// Default retry policy for all calls
RetryPolicy default_retry = 1;
// Idempotency key generation strategy
IdempotencyStrategy idempotency_strategy = 2;
// Backpressure handling
BackpressureHandling backpressure = 3;
// Circuit breaker configuration
CircuitBreakerConfig circuit_breaker = 4;
}
enum IdempotencyStrategy {
UUID_PER_REQUEST = 0;
CONTENT_HASH = 1; // Hash of request body + method
BUSINESS_KEY = 2; // Client-provided business key
TIME_WINDOW = 3; // Time-based window deduplication
}
message BackpressureHandling {
bool enabled = 1;
enum Action {
BLOCK = 0; // Block until backpressure clears
REJECT = 1; // Fail immediately with error
SHED = 2; // Randomly drop events
PRIORITY = 3; // Prioritize certain event types
}
Action action = 2;
int32 max_block_time_ms = 3; // Max time to block
map<string, int32> priority_rules = 4; // Event type -> priority
}
message CircuitBreakerConfig {
int32 failure_threshold = 1; // Consecutive failures to trip
int32 reset_timeout_ms = 2; // Time before trying again
int32 half_open_max_calls = 3; // Max calls in half-open state
bool enabled = 4;
}
6. Guarantees and SLAs
message ServiceLevelAgreement {
// RPC guarantees
double rpc_availability = 1; // e.g., 99.99%
int64 rpc_max_latency_ms_p99 = 2; // 99th percentile latency
int64 rpc_timeout_ms = 3; // Default timeout
// Event guarantees
double event_durability = 4; // e.g., 99.999999% (11 9's)
int64 event_max_latency_ms_p99 = 5;
int64 event_retention_days = 6;
// Backpressure guarantees
bool backpressure_signaling = 7; // Must signal when >80% capacity
int32 backpressure_reaction_time_ms = 8; // Time to react to signal
}
7. Implementation Examples
# Python-like pseudo-implementation
class HybridClient:
def __init__(self, config: ClientConfig):
self.config = config
self.idempotency_store = IdempotencyStore()
self.tracer = Tracer()
self.circuit_breaker = CircuitBreaker(config.circuit_breaker)
async def rpc_call(self,
method: str,
payload: bytes,
idempotency_key: Optional[str] = None,
trace: Optional[TraceContext] = None,
retry_policy: Optional[RetryPolicy] = None) -> bytes:
# Generate idempotency key if not provided
if not idempotency_key:
idempency_key = self._generate_idempotency_key(method, payload)
# Start/extract trace
if not trace:
trace = self.tracer.start_span(method)
# Circuit breaker check
if self.circuit_breaker.is_open():
raise CircuitBreakerOpenError()
# Execute with retries
last_error = None
policy = retry_policy or self.config.default_retry
for attempt in range(policy.max_attempts + 1):
try:
request = HybridRpcRequest(
method=method,
payload=payload,
idempotency=IdempotencyKey(key=idempotency_key),
trace=trace,
retry_policy=policy
)
response = await self._transport.send(request)
if response.result.error:
error = response.result.error
if self._should_retry(error, policy):
delay = self._calculate_backoff(attempt, policy)
await asyncio.sleep(delay)
continue
else:
raise RpcError(error)
return response.result.success
except Exception as e:
last_error = e
if attempt < policy.max_attempts:
delay = self._calculate_backoff(attempt, policy)
await asyncio.sleep(delay)
raise last_error
async def produce_event(self,
event_type: str,
payload: bytes,
trace: Optional[TraceContext] = None,
priority: int = 0) -> str:
"""Produce event with backpressure handling"""
event = HybridEvent(
event_type=event_type,
source_service=self.service_name,
payload=payload,
trace=trace or self.tracer.current_span(),
timestamp=time.time_ms()
)
# Check backpressure
status = await self.backpressure_client.get_status()
if status.signal.level >= BackpressureSignal.CRITICAL:
if self.config.backpressure.action == BackpressureHandling.BLOCK:
await self._wait_for_backpressure_clear(status)
elif self.config.backpressure.action == BackpressureHandling.REJECT:
raise BackpressureError("System under critical load")
elif self.config.backpressur.action == BackpressureHandling.SHED:
if not self._should_shed_event(event_type, priority):
raise BackpressureError("Event shed due to backpressure")
response = await self.event_producer.produce(event)
return response.event_id
8. Server Implementation Pattern
// Java-like server implementation
public class HybridRpcServer {
private final IdempotencyStore idempotencyStore;
private final Tracer tracer;
private final BackpressureMonitor backpressureMonitor;
private final EventProducer eventProducer;
public HybridRpcResponse handleRequest(HybridRpcRequest request) {
Span span = tracer.newChild(request.getTrace());
try (Scope scope = span.makeCurrent()) {
// Check backpressure before processing
BackpressureSignal signal = backpressureMonitor.currentSignal();
if (signal.getLevel() == BackpressureSignal.Critical) {
return errorResponse(Error.newBuilder()
.setType(Error.Type.BACKPRESSURE)
.setMessage("Server under backpressure")
.setRetryAfterMs(signal.getRecommendedDelayMs())
.build());
}
// Check idempotency
String cachedResponse = idempotencyStore.get(request.getIdempotency().getKey());
if (cachedResponse != null) {
return HybridRpcResponse.newBuilder()
.setSuccess(ByteString.copyFromUtf8(cachedResponse))
.setIdempotentReplay(true)
.setTrace(request.getTrace())
.build();
}
// Process request
String result = processRpc(request.getMethod(), request.getPayload());
// Store idempotency
idempotencyStore.store(
request.getIdempotency().getKey(),
result,
request.getIdempotency().getTtlSeconds()
);
// Emit telemetry event
emitTelemetryEvent("rpc.completed", request, result);
return HybridRpcResponse.newBuilder()
.setSuccess(ByteString.copyFromUtf8(result))
.setTrace(span.context().toTraceContext())
.build();
} catch (Exception e) {
span.error(e);
throw e;
}
}
private void emitTelemetryEvent(String eventType,
HybridRpcRequest request,
String result) {
// Propagate trace context
TraceContext trace = span.context().toTraceContext();
HybridEvent event = HybridEvent.newBuilder()
.setEventType(eventType)
.setSourceService(serviceName)
.setPayload(createEventPayload(request, result))
.setTrace(trace)
.build();
// Fire and forget with best effort
try {
eventProducer.produceAsync(event);
} catch (BackpressureException e) {
// Log but don't fail the RPC
logger.warn("Failed to emit telemetry event", e);
}
}
}
9. Configuration Example (YAML)
rpc_client:
default_retry:
max_attempts: 3
initial_interval_ms: 100
max_interval_ms: 5000
multiplier: 2.0
jitter_factor: 0.2
retry_on: "SERVER_ERROR"
idempotency:
strategy: "CONTENT_HASH"
key_prefix: "rpc:"
ttl_seconds: 86400
backpressure:
enabled: true
action: "BLOCK"
max_block_time_ms: 5000
circuit_breaker:
enabled: true
failure_threshold: 5
reset_timeout_ms: 60000
rpc_server:
idempotency:
storage: "redis"
ttl_seconds: 86400
max_keys: 1000000
backpressure:
queue_size_threshold: 10000
memory_threshold_mb: 4096
cpu_threshold_percent: 80
cool_down_ms: 5000
tracing:
enabled: true
sampling_rate: "0.1"
exporter_endpoint: "http://jaeger:14268/api/traces"
event_producer:
batch_size: 100
batch_timeout_ms: 100
async: true
compression: "gzip"
event_consumer:
max_concurrent: 10
prefetch_count: 100
backpressure_signal_endpoint: "http://localhost:8080/backpressure"
sla:
rpc_availability: 0.9999
rpc_max_latency_ms_p99: 500
event_durability: 0.999999
event_max_latency_ms_p99: 1000
10. Key Design Decisions
-
Idempotency:
- Server-side storage with TTL
- Client-provided keys with namespace scoping
- Replay detection via stored responses
-
Retries:
- Client-controlled with exponential backoff + jitter
- Server should be idempotent to handle retries
- Different policies for different error types
-
Tracing:
- W3C Trace Context propagation
- Automatic span creation for each RPC/event
- Baggage propagation for cross-cutting concerns
-
Backpressure:
- Broker-to-producer signaling
- Multiple handling strategies (block, reject, shed)
- Priority-based shedding for events
- Circuit breaker integration
-
Hybrid Nature:
- Same tracing context flows through RPC and events
- Events can be emitted from RPC handlers
- RPCs can be triggered by events
11. Error Handling Taxonomy
// Standardized error codes
enum StandardErrorCode {
OK = 0;
// Idempotency errors
IDEMPOTENCY_KEY_MISSING = 1000;
IDEMPOTENCY_CONFLICT = 1001;
IDEMPOTENCY_EXPIRED = 1002;
// Backpressure errors
BACKPRESSURE_CRITICAL = 2000;
BACKPRESSURE_ELEVATED = 2001;
QUEUE_FULL = 2002;
// Retry errors
RETRY_EXHAUSTED = 3000;
RETRY_DISABLED = 3001;
// Tracing errors
TRACE_INVALID = 4000;
TRACE_PROPAGATION_FAILED = 4001;
// System errors
CIRCUIT_BREAKER_OPEN = 5000;
TIMEOUT = 5001;
UNKNOWN = 9999;
}
This contract provides:
- ✅ Idempotency via idempotency keys with server-side storage
- ✅ Retries with configurable exponential backoff + jitter
- ✅ Tracing with W3C Trace Context propagation
- ✅ Backpressure with signaling and multiple handling strategies
- ✅ Hybrid integration where RPC and events share context
- ✅ Observability through tracing, metrics, and structured logging
The contract is transport-agnostic (can use HTTP/gRPC/message queues) and includes both synchronous RPC and asynchronous event patterns with proper flow control.