Skip to content

Commit 6fd8d3d

Browse files
authored
Add documentation for KafkaContext.heartbeat usage
1 parent f905f95 commit 6fd8d3d

File tree

1 file changed

+31
-9
lines changed

1 file changed

+31
-9
lines changed

content/microservices/kafka.md

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -313,16 +313,18 @@ To access the original Kafka `IncomingMessage` object, use the `getMessage()` me
313313
```typescript
314314
@@filename()
315315
@MessagePattern('hero.kill.dragon')
316-
killDragon(@Payload() message: KillDragonMessage, @Ctx() context: KafkaContext) {
317-
const originalMessage = context.getMessage();
318-
const { headers, partition, timestamp } = originalMessage;
319-
}
320-
@@switch
321-
@Bind(Payload(), Ctx())
322-
@MessagePattern('hero.kill.dragon')
323-
killDragon(message, context) {
316+
async killDragon(@Payload() message: KillDragonMessage, @Ctx() context: KafkaContext) {
324317
const originalMessage = context.getMessage();
325-
const { headers, partition, timestamp } = originalMessage;
318+
const heartbeat = context.getHeartbeat();
319+
320+
// Do some slow processing:
321+
await doWorkPart1();
322+
323+
// Send heartbeat when it's possible in order to not exceed the sessionTimeout
324+
await heartbeat();
325+
326+
// Do some slow processing again:
327+
await doWorkPart2();
326328
}
327329
```
328330

@@ -342,6 +344,26 @@ interface IncomingMessage {
342344
}
343345
```
344346

347+
If your endpoint involves slow processing time for each message you should consider calling `heartbeat` callback, use `getHeartbeat()` method of `KafkaContext` which will send heartbeat to the broker, as follows:
348+
349+
```typescript
350+
@@filename()
351+
@MessagePattern('hero.kill.dragon')
352+
killDragon(@Payload() message: KillDragonMessage, @Ctx() context: KafkaContext) {
353+
const originalMessage = context.getMessage();
354+
const { headers, partition, timestamp } = originalMessage;
355+
}
356+
@@switch
357+
@Bind(Payload(), Ctx())
358+
@MessagePattern('hero.kill.dragon')
359+
killDragon(message, context) {
360+
const originalMessage = context.getMessage();
361+
const { headers, partition, timestamp } = originalMessage;
362+
}
363+
```
364+
365+
366+
345367
#### Naming conventions
346368

347369
The Kafka microservice components append a description of their respective role onto the `client.clientId` and `consumer.groupId` options to prevent collisions between Nest microservice client and server components. By default the `ClientKafka` components append `-client` and the `ServerKafka` components append `-server` to both of these options. Note how the provided values below are transformed in that way (as shown in the comments).

0 commit comments

Comments
 (0)