RPC
Trait-based RPC framework with automatic route generation, type-safe serialization, and structured error handling.
import wvlet.uni.http.rpc.*
// Define a service trait
trait UserService:
def getUser(id: Long): User
def createUser(name: String, email: String): User
// Create a router from the implementation
val router = RPCRouter.of[UserService](UserServiceImpl())
// Generates: POST /<package>.UserService/getUser, POST /<package>.UserService/createUserDefining an RPC Service
Define your service API as a Scala trait, then provide an implementation:
case class User(id: Long, name: String, email: String)
trait UserService:
def getUser(id: Long): User
def createUser(name: String, email: String): User
def listUsers(limit: Int = 10): Seq[User]
class UserServiceImpl extends UserService:
def getUser(id: Long): User =
User(id, "Alice", "alice@example.com")
def createUser(name: String, email: String): User =
User(1L, name, email)
def listUsers(limit: Int): Seq[User] =
Seq(User(1L, "Alice", "alice@example.com"))Methods can return Rx[T] for asynchronous responses — the router unwraps the return type automatically:
import wvlet.uni.rx.Rx
trait AsyncUserService:
def getUser(id: Long): Rx[User]Creating an RPC Router
RPCRouter.of[T] uses compile-time reflection to extract method metadata and build routes:
val impl = UserServiceImpl()
val router = RPCRouter.of[UserService](impl)
// Inspect generated routes
router.routes.foreach { route =>
println(s"${route.path}")
}
// /com.example.api.UserService/getUser
// /com.example.api.UserService/createUser
// /com.example.api.UserService/listUsers
// Look up a specific route
val route = router.findRoute("getUser")All routes use POST with the path format /{serviceName}/{methodName}, where serviceName is the trait's fully qualified name.
The type argument T decides both the route prefix and the endpoint set, so pass the service trait. RPCRouter.of(impl) also compiles, but T is then inferred from the argument's static type: given a UserServiceImpl value, the routes become /com.example.api.UserServiceImpl/..., and a client built with RPCClient.of[UserService] gets 404 Not Found for every call. Writing RPCRouter.of[UserService](impl) keeps the two sides on the same path.
Every public method of T becomes an endpoint, including methods inherited from your own base traits (trait UserService extends CrudApi[User] serves the CrudApi methods too). Methods inherited from library traits (scala.*, java.*, uni's logging mixins such as LogSupport) are never exposed. Annotate a method with @rpcIgnore to keep it out of the RPC endpoints:
trait UserService:
def getUser(id: Long): User
@rpcIgnore
def cacheStats: String = "..." // callable in-process onlyRPCClient applies the same rules, so client and server agree on the endpoint set.
Request Format
Parameters are sent as JSON in the request body:
{
"request": {
"id": 42
}
}Parameter names are matched flexibly — userId, user_id, and user-id all match the same parameter. Missing optional parameters (Option[T]) default to None, and parameters with default values use those defaults.
Generating a Client
Instead of hand-writing request URLs and JSON, generate a type-safe client from the same service trait with the sbt-uni plugin. The generated client mirrors the trait's methods, so calls are checked by the compiler.
JVM build-time only
Client generation runs at build time on the JVM via sbt. The generated client is ordinary code that compiles for any platform the trait supports.
Enable the plugin
In project/plugins.sbt:
addSbtPlugin("org.wvlet.uni" % "sbt-uni" % "2026.2.0")In build.sbt, enable UniPlugin on the project that should contain the generated client, depend on the project that defines the service trait, and list your generation targets:
lazy val app = project
.enablePlugins(UniPlugin)
.dependsOn(api) // project containing UserService
.settings(
uniHttpClients := Seq("com.example.api.UserService:rpc")
)uniHttpClients is wired into Compile / sourceGenerators, so clients are regenerated and compiled automatically on the next compile. Generation runs uni's HttpCodeGeneratorMain in a forked JVM, from the uni version the app depends on (also for Scala.js apps), and it skips files whose content is unchanged.
Target spec format
Each entry is "fullyQualifiedTrait:clientType[:targetPackage]":
| Part | Values | Notes |
|---|---|---|
clientType | sync, async, both, rpc | rpc is an alias for sync |
targetPackage | optional | defaults to the trait's package + .client |
uniHttpClients := Seq(
"com.example.api.UserService:rpc", // SyncClient, default package
"com.example.api.OrderService:both:com.example.client" // Sync + Async clients
)Override the output directory with uniHttpCodegenOutDir (defaults to Compile / sourceManaged).
Using the generated client
Generation produces an object <ServiceName>Client containing a SyncClient and/or AsyncClient, each wrapping an HTTP client. Construct one over a configured client pointed at the server's base URL:
import wvlet.uni.http.Http
import com.example.client.UserServiceClient
// Sync — methods return the declared types directly
val sync = UserServiceClient.SyncClient(
Http.client.withBaseUri("http://localhost:8080").newSyncClient
)
val user: User = sync.getUser(42)
// Async — methods return Rx[...]
val async = UserServiceClient.AsyncClient(
Http.client.withBaseUri("http://localhost:8080").newAsyncClient
)
async.getUser(42).map(user => println(user.name))A trait method that returns Rx[A] returns A from SyncClient and Rx[A] from AsyncClient. The generator reads types from compiled classes, where Scala erases primitive type arguments, so Rx[Int] or Seq[Long] come out as Rx[Any] or Seq[Any]; wrap such values in a case class to keep their type. A method that returns RxStream[A] is streamed by AsyncClient, which returns RxStream[A] for it; SyncClient leaves such methods out.
Under the hood the generated methods delegate to RPCClient.of[UserService], which serializes arguments and decodes responses with Weaver — the same wire format the RPC router expects, so client and server stay in sync.
Writing a client by hand
Without codegen, write the client with RPCClient directly. RPCClient.of[T] holds the method codecs for T, and newSyncClient(http) or newAsyncClient(http) binds them to an HTTP client. call takes the method name followed by its arguments in declaration order:
import wvlet.uni.http.{Http, HttpSyncClient}
import wvlet.uni.http.rpc.RPCClient
class UserServiceClient(http: HttpSyncClient) extends UserService:
private val rpc = RPCClient.of[UserService].newSyncClient(http)
def getUser(id: Long): User = rpc.call("getUser", id)
def createUser(name: String, email: String): User = rpc.call("createUser", name, email)
def listUsers(limit: Int): Seq[User] = rpc.call("listUsers", limit)
val client = UserServiceClient(Http.client.withBaseUri("http://localhost:8080").newSyncClient)The async form returns Rx[A]:
val rpc = RPCClient
.of[UserService]
.newAsyncClient(Http.client.withBaseUri("http://localhost:8080").newAsyncClient)
rpc.call[User]("getUser", 42L).map(user => println(user.name))An RPCClient has no connection state, so one instance can be shared by any number of bound clients. The lower-level callSync(http, name, args) and callAsync(http, name, args) take the HTTP client on every call.
Streaming Results
A method can deliver more than one value: a model's tokens, progress updates, or log lines. Declare it with the return type RxStream[A] (wvlet.uni.rx.RxStream), an Rx that marks the method as streaming. Call it with stream instead of call, and the client receives each value as the server emits it:
import wvlet.uni.rx.{Rx, RxStream}
trait ChatApi:
def streamReply(prompt: String): RxStream[String]
class ChatApiImpl extends ChatApi:
// Wrap any Rx: a model's token stream, a queue, an interval
def streamReply(prompt: String): RxStream[String] =
RxStream(Rx.fromSeq(Seq("Hello", ", ", prompt)))
val rpc = RPCClient.of[ChatApi].newAsyncClient(Http.client.newAsyncClient)
rpc.stream[String]("streamReply", "Uni").run(token => print(token))RxStream(rx) runs exactly like rx. Rx operators such as map return a plain Rx, so wrap the finished chain. The router needs nothing more. stream sends Accept: text/event-stream, so the dispatcher answers with Server-Sent Events: one data: event per value, carrying its JSON. The dispatcher streams only when text/event-stream is the first type in Accept. A plain call to the same method still gets one JSON value, the first one. If the server answers without streaming, because it predates streaming RPC, the Rx fails with UNIMPLEMENTED_U8.
- Errors. A failure before the method returns gets the usual error response, which fails the
Rxwith anHttpException, as a unary call does. A failure after the stream started is sent as anrpc-errorevent carrying the RPC error JSON. It ends the stream and fails theRxwith thatServiceException. - No retry. A stream that has started cannot be replayed, so streaming calls are sent once.
- Cancellation. Cancelling the
Rx(an unsubscribe, ortake(n)) stops the server stream: the client aborts the request (fetch, the JVM client, and libcurl on Scala Native), and the server cancels the method'sRxwhen the connection closes. In Electron, the preload's cancel function tells the main process (see Electron). - Transports. HTTP servers stream on the JVM, Node.js, and Scala Native. Clients stream with
fetch(browser, Node.js), on the JVM, and on Scala Native. In Electron, the IPC transport streams too, once the preload bridge exposesstream(see Electron).
Generated clients
The return type tells the generated AsyncClient which call to make:
trait ChatApi:
def listConversations(): Rx[Seq[Conversation]] // call: one value
def streamReply(prompt: String): RxStream[String] // stream: every valueThe server and the wire format are the same for both: the dispatcher streams any Rx when the client asks, and a plain call of an RxStream method still gets the first value. A hand-written client picks call or stream itself. There is no synchronous stream call, so SyncClient leaves RxStream methods out.
The uni-harness example streams chat replies this way, in Electron and in the browser.
RPC Status Codes
ServiceStatus (in wvlet.uni.http) provides structured error codes organized by category. RPC, Electron IPC, and MCP servers share these statuses. Before version 2026.1.42 it was called RPCStatus, and the old names remain as deprecated aliases in wvlet.uni.http.rpc. The aliases keep source compatibility only: recompile libraries built against the old names.
| Category | HTTP Status | Retryable | Description |
|---|---|---|---|
SUCCESS (S) | 2xx | — | Request completed successfully |
USER_ERROR (U) | 4xx | No | Client error |
INTERNAL_ERROR (I) | 5xx | Yes | Server error |
RESOURCE_EXHAUSTED (R) | 429 | Yes (with backoff) | Rate/quota limits exceeded |
Common Status Codes
import wvlet.uni.http.ServiceStatus
// User errors (not retryable)
ServiceStatus.INVALID_REQUEST_U1 // 400 - Malformed request
ServiceStatus.INVALID_ARGUMENT_U2 // 400 - Bad parameter values
ServiceStatus.NOT_FOUND_U5 // 404 - Resource not found
ServiceStatus.ALREADY_EXISTS_U6 // 409 - Resource already exists
ServiceStatus.UNAUTHENTICATED_U13 // 401 - Authentication required
ServiceStatus.PERMISSION_DENIED_U14 // 403 - Forbidden
// Server errors (retryable)
ServiceStatus.INTERNAL_ERROR_I0 // 500 - Generic server error
ServiceStatus.UNAVAILABLE_I2 // 503 - Service unavailable
ServiceStatus.TIMEOUT_I3 // 504 - Timeout
// Resource errors (retry with backoff)
ServiceStatus.EXCEEDED_RATE_LIMIT_R2 // 429 - Rate limitedError Handling
Throwing RPC Errors
import wvlet.uni.http.{ServiceException, ServiceStatus}
class UserServiceImpl extends UserService:
def getUser(id: Long): User =
if id <= 0 then
throw ServiceStatus.INVALID_ARGUMENT_U2
.newException(s"Invalid user id: ${id}")
// ...ServiceException
ServiceException carries a status code and serializes to JSON or MessagePack for wire transport:
val ex = ServiceStatus.NOT_FOUND_U5.newException("User not found")
// Serialize
val json: String = ex.toJson
val response = ex.toResponse // HTTP response with status header
// Deserialize
val recovered = ServiceException.fromJson(json)
val fromResp = ServiceException.fromResponse(response)
// Application-specific error codes
val appEx = ServiceStatus.USER_ERROR_U0
.newException("Insufficient balance", appErrorCode = Some(1001))Stack Traces
Error responses carry no stack trace by default, on every platform and transport. Stack frames reveal internal class names, file names, and line numbers, so a client sees only the status, message, and appErrorCode. The server still logs unexpected exceptions with their stack traces.
For development, create the dispatcher with withDetailedErrors(true) (RPCHandler(...).withDetailedErrors(true) on Netty) to add the server-side stack trace as a stackTrace array of frames (className, methodName, fileName, lineNumber), the same shape as Airframe RPC:
val dispatcher = RPCDispatcher(router).withDetailedErrors(true) // development onlyElectron IPC (ElectronRPCServer) has no such switch and never sends stack traces.
In detailed mode UNAUTHENTICATED_U13 and PERMISSION_DENIED_U14 errors still omit stack traces, and so does an exception marked with noStackTrace:
throw ServiceStatus.INVALID_ARGUMENT_U2.newException("Invalid input").noStackTraceUnexpected (non-ServiceException) exceptions from a handler are wrapped as INTERNAL_ERROR_I0 with no message or stack trace, unless detailed errors are enabled.
To always send the stack trace of one specific error, construct it with ServiceException(status, message, includeStackTrace = Some(true)). Do this only when every client may see server internals.
On the client, ServiceException.fromJson, fromMsgPack, and fromResponse restore the frames when the body has a stackTrace field, so responses from older Uni servers and Airframe RPC servers still decode.
Best Practices
- No method overloading in RPC traits — the router rejects overloaded method names
- Use specific status codes (
NOT_FOUND_U5) over generic ones (USER_ERROR_U0) - Keep service traits in a shared module so clients can reference the same interface
- Use
Rx[T]return types for async operations to avoid blocking server threads - Use default parameter values to maintain backward compatibility when adding new parameters