Kest

Search

Search the documentation

Microservices

Overview

Let services talk to each other through messages instead of HTTP calls.

A large system is often several services (orders, payments, shipping). They need to talk. You can use HTTP, but a message-based style has advantages: the services do not need to know each other's address, a message can wait while a service restarts, and one message can reach many services. microservices is @nestjs/microservices: services talk by sending messages through a transport (a message broker, or a TCP connection).

Two kinds of message:

KindMeaningYou get
Message (request/reply)"compute this and answer me"a reply (or an error)
Event (fire and forget)"this happened"nothing; any number of services may react
Loading diagram…

Handling messages

@Injectable
class MathHandlers {
    @MessagePattern("sum") fun sum(numbers: List<Int>): Int = numbers.sum()                       // request/reply
    @MessagePattern("greet") fun greet(name: String, ctx: MessageContext) = "hello $name via ${ctx.transport}"
    @EventPattern("order.created") fun onOrder(e: OrderCreated) { /* no reply */ }               // event
    @Role("ADMIN") @MessagePattern("admin.reset") fun reset() = "done"
}

A handler is a normal method on a provider. Its pattern ("sum") is the message's name. Handlers are found at build time (the same @Discoverable mechanism as @Cron). The parameter is the payload, decoded with the application's codec (and validated if you use a pipe); a MessageContext parameter gives the transport and pattern.

Start serving with a transport (see Transports compared):

val app = Kest.run<AppModule>(args)
app.connectMicroservice(TcpOptions(4000))       // or RedisOptions, NatsOptions, KafkaOptions, RmqOptions, MqttOptions

Calling

import(ClientsModule.register { client("SHOP", TcpOptions(4000)) })   // in the caller's module     // one client per service you call
val total: Int? = client.send("sum", listOf(1, 2, 3))           // waits for the reply (10 s by default); null when the handler returned null
client.emit("order.created", OrderCreated("o1"))                // fire and forget

send<T>(pattern, data, timeout, headers) waits for the answer and throws RpcException if the handler failed (with its status) or nobody answered in time (status 408). ClientProxy.headers["authorization"] = "Bearer ..." adds headers to every message.

The pipeline applies

Guards, @Role, interceptors, filters and pipes run on message handlers exactly as on HTTP routes: Guards, Pipes, Interceptors, Exception filters. What a guard sees as request headers are the message's headers (or gRPC metadata), so a token can ride along with the message.

Starting a microservice

NestJS NestFactory.createMicroservice is createMicroservice: a container without HTTP, listening on one transport.

fun main() {
    val service = createMicroservice<AppModule>(TcpOptions(port = 4000))   // or KafkaOptions, RmqOptions, NatsOptions, MqttOptions, RedisOptions
    service.listen()
    service.await()                                                        // returns after close(), e.g. on SIGTERM
}

Every transport has an options class (NestJS MicroserviceOptions), with the settings you would give NestJS: hosts, ports, the consumer group, the queue, retry attempts and delays for the first connection, and the handler retry for events.

Hybrid applications

One container serves HTTP and one or more microservice transports at once, sharing providers. Connect the transports, then start them all, as NestJS's connectMicroservice and startAllMicroservices do:

val app = Kest.run<AppModule>(args)
app.connectMicroservice(RedisOptions("redis", 6379))
app.connectMicroservice(TcpOptions(port = 4000))
app.startAllMicroservices()
app.http(NettyHttpAdapter(8080))

Clients, asynchronous calls and registration

ClientsModule.register { client("SHOP", TcpOptions(4000)) } gives you a ClientProxy by name. ClientsModule.registerAsync { resolver -> ... } builds the clients from the container, for example from configuration. A proxy offers send (blocking), ask (suspends, so a coroutine waits without holding a thread), sendAsync (a future) and emit (fire and forget). A pattern can be a string or an object, mapOf("cmd" to "sum"), matched by content as in NestJS.

val total: Int? = shop.ask("sum", listOf(1, 2, 3))           // in a suspend function
shop.emit("order.placed", OrderPlaced("o1", 42))

Request/reply or events?

  • Request/reply when the caller needs the answer to continue (check the price, charge the card). The caller waits, and a slow or dead service shows up as a timeout: protect it with resilience.
  • Events when the sender does not care who reacts (an order was placed). Use the transactional outbox so the event is never lost or sent for a rolled-back change.

When the broker restarts

A server and a client that are already connected carry on by themselves when the broker restarts; nothing needs restarting. This is tested against the real brokers: each is restarted with docker restart while a server and client are connected.

TransportHow it recovers
Redisthe subscriber reconnects with a growing pause (0.2 s up to 3 s) and subscribes again
NATSthe client library reconnects and resubscribes
MQTTautomatic reconnect, and subscriptions are made again on every reconnect (the session is clean, so the broker forgot them)
RabbitMQautomatic connection and topology recovery; messages that were not acknowledged come back, marked as redelivered; the reply queue has a name the client chose, so it comes back under the same name
Kafkathe consumer is supervised: if it fails it is closed and created again, and resumes from its last committed offset

Requests made while the broker is down fail with a timeout (408) rather than waiting for ever, so retry in the caller (@Retry).

Concurrency and delivery

For what each transport promises, what a handler can see about its message, and how failures are retried and dead-lettered, see Delivery and dead letters.

Each message is handled on its own virtual thread, so handlers run in parallel and must be thread-safe. Delivery depends on the transport: TCP and the request/reply brokers answer each request once; Kafka, RabbitMQ and MQTT are at least once when the handler fails and the message is redelivered, so make handlers idempotent (Idempotency keys).

Limits

  • Streaming responses: on the message-broker transports a request gets one reply; there is no stream of replies (gRPC streams, see gRPC).
  • Cluster failover: recovery is tested by restarting a single broker under a connected server and client, not by failing over inside a broker cluster, and messages sent while the broker is down are not queued by the client: they time out.
  • Interop with NestJS: the TCP and Redis wire formats follow NestJS's, but the services were never run against a real NestJS peer.
  • Serializers: the wire format is the NestJS envelope in JSON; a custom serializer per transport is not in this release.
  • gRPC stubs: GrpcClient calls a service by its name and method name, with your own message classes. Generated typed stubs are not in this release.
  • Errors in handlers are reported to error monitoring (source=microservice); trace context is not propagated through brokers yet.

Read more