Tag Archives: akka streams

Dynamic IoT Streams With Akka GRPC

Having covered a basic use case for gRPC streaming of IoT device states in the previous blog post, we’re now moving onto a slightly more complex scenario that involves dynamically broadcasting response streams from the server to any participating clients.

Rather than having each of the gRPC clients receiving the IoT states update responses to their own request streams, the responses are now being broadcast to all participating clients, making it possible for any given client to work with the received states update of devices inside a property originally processed by other clients.

Akka gRPC streaming

Recall that we were leveraging Akka gRPC to:

  1. generate service interfaces from the Protobuf service schema that get implemented as Scala classes and Akka stream components to create HttpRequest => Future[HttpResponse] routes in the Akka-HTTP server that supports HTTP/2
  2. generate gRPC stubs through implementing the service interfaces with Akka Streams API to invoke the remote services
Akka gRPC Streaming

Dynamically broadcasting IoT streams

Just like in the previous use case, our IoT system of sensor devices consists of a gRPC server simulating algorithmic changes to device states as response streams to the requesting gRPC clients. There can be many clients participating/leaving at any time.

In our new use case, the server broadcasts response streams to requests from all clients and each client receives all the stream elements since its participation. It’s similar in some way to a dynamic pub/sub channel in which the gRPC clients subscribe to a service-topic published by the gRPC server.

How do we create such a channel? As shown in one of the GreeterService examples available at Lightbend developers guide, we could create one by coupling a MergeHub with a BroadcastHub. For more details, another blog post of mine covers the very topic.

A new Protobuf service

A majority of the source code described in the previous blog post remains unchanged, as we’re only adding a new RPC service along with its implementation.

First, we declare the new RPC service broadcastIotUpdate() in iotstream.proto under src/main/protobuf/.

service IotStreamService {
    rpc sendIotUpdate(stream StatesUpdateRequest) returns (stream StatesUpdateResponse) {}
    rpc broadcastIotUpdate(stream StatesUpdateRequest) returns (stream StatesUpdateResponse) {}
}

We then add the implementation of broadcastIotUpdate() in class IotStreamServiceImpl.

val (inHub: Sink[StatesUpdateRequest, NotUsed], outHub: Source[StatesUpdateResponse, NotUsed]) =
  MergeHub.source[StatesUpdateRequest]
    .via(updateIotFlow)
    .toMat(BroadcastHub.sink[StatesUpdateResponse])(Keep.both)
    .run()

val dynamicPubSubFlow: Flow[StatesUpdateRequest, StatesUpdateResponse, NotUsed] =
  Flow.fromSinkAndSource(inHub, outHub)

...

@Override
def broadcastIotUpdate(requests: Source[StatesUpdateRequest, NotUsed]): Source[StatesUpdateResponse, NotUsed] =
  requests.via(dynamicPubSubFlow).backpressureTimeout(backpressureTMO)

As shown in the above snippet, we “sandwich” updateIotFlow (which simulates algorithmic IoT states update) between a MergeHub and a BroadcastHub to materialize a tuple of sink and source, followed by turning them into the dynamicPubSubFlow via Akka Stream’s fromSinkAndSource(). The created flow will then serve like a dynamic pub/sub channel funneling incoming request streams from the gRPC clients to broadcast the response streams with updated states to all participating clients.

As for class IotStreamClient, we add a new command line argument, broadcastYN (1=Yes, 0=No), to the main() function’s argument list to indicate whether broadcast of response streams is wanted. The client application will call the specific RPC service in accordance with the value of broadcastYN.

val responseStream: Source[StatesUpdateResponse, NotUsed] = {
  if (broadcastYN == 0)
    client.sendIotUpdate(requestStream)
  else
    client.broadcastIotUpdate(requestStream)
}

The following diagram highlights the gRPC server/clients components, and the rest of the IoT system that manages the individual remote sensor devices. Note that the IoT Manager sub-system isn’t part of the application we’re focusing on. The sub-system could be designed on top of gRPC as well, or Akka Actors (i.e. similar to the Actor-based IotManager), or any other suitable tech stack.

IoT Streaming with Akka gRPC

Full source code for the gRPC client/server components is available at this GitHub repo.

Final thoughts

It should be noted that this is a simplified use case primarily for demonstrating how device states update from the gRPC server can be dynamically broadcast to the requesting clients. To strengthen the use case, we could maintain a key-value cache using Redis with unique device IDs as keys subject to a pre-set TTL (time-to-live) to prevent multiple gRPC clients processing for the same device simultaneously.

In addition, we might also log in persistence storages the who-what-and-when (i.e. client ID / states / timestamp) of the device states update, or if warranted by the business requirement, putting in place a distributed committed log system with Apache Kafka. Such enhancement would enable the Akka Streams-baced gRPC tech stack to provide a robust streaming mechanism comparable to those solutions like using Akka Actors with distributed pub/sub and persistence journal on clusters.

Sample output

Appended is sample output from the gRPC server and 3 gRPC clients. As shown in the output, one could mix and match clients with different broadcast options, in which case the group of clients with broadcast on will share among themselves all streams responded by the server to requests from themselves, whereas each member of the broadcast-off group will get only responded streams originated by itself.

Terminal #1: gRPC Server

% ./sbt "runMain akkagrpc.IotStreamServer"
[info] ...
[info] done compiling
[info] running (fork) akkagrpc.IotStreamServer 
[info] [2023-10-31 11:38:03,227] [INFO] [akka.event.slf4j.Slf4jLogger] [IotStreamServer-akka.actor.default-dispatcher-3] [] - Slf4jLogger started
[info] [Server] gRPC server bound to 127.0.0.1:8080

Terminal #2: gRPC Client1 — broadcast ON (broadcastYN = 1)

% ./sbt "runMain akkagrpc.IotStreamClient client1 1 1000 1019"
[info] welcome to sbt 1.9.6 (Oracle Corporation Java 11.0.19)
[info] loading global plugins from /Users/leo/.sbt/1.0/plugins
[info] loading settings for project akka-grpc-iot-stream-build from plugins.sbt ...
[info] loading project definition from /Users/leo/intellij/akka-grpc-iot-stream/project
[info] loading settings for project akka-grpc-iot-stream from build.sbt ...
[info] set current project to akka-grpc-iot-stream (in build file:/Users/leo/intellij/akka-grpc-iot-stream/)
[info] running (fork) akkagrpc.IotStreamClient client1 1 1000 1019
[info] [2023-10-31 11:53:39,910] [INFO] [akka.event.slf4j.Slf4jLogger] [IotStreamClient-akka.actor.default-dispatcher-3] [] - Slf4jLogger started
[info] Performing streaming requests from client1 ...
[info] [client1] REQUEST: 1000 5e468f SecurityAlarm | State: 0, Setting: 1
[info] [client1] REQUEST: 1000 70a7bf Lamp | State: 0, Setting: 2
[info] [client1] REQUEST: 1001 a6d07c Lamp | State: 1, Setting: 1
[info] [client1] REQUEST: 1001 b224cf SecurityAlarm | State: 0, Setting: 4
[info] [client1] REQUEST: 1001 df00a1 SecurityAlarm | State: 1, Setting: 4
[info] [client1] REQUEST: 1002 5d9abe Thermostat | State: 1, Setting: 69
[info] [client1] REQUEST: 1002 283a39 Thermostat | State: 1, Setting: 60
[info] [client1] REQUEST: 1002 70b354 SecurityAlarm | State: 0, Setting: 5
[info] [client1] REQUEST: 1002 c12ac7 Thermostat | State: 0, Setting: 66
[info] [client1] REQUEST: 1003 2587a9 Lamp | State: 0, Setting: 2
[info] [client1] REQUEST: 1004 f5732a Thermostat | State: 1, Setting: 62
[info] [client1] REQUEST: 1004 c7aaf1 Lamp | State: 0, Setting: 1
[info] [client1] RESPONSE: [requester: client1] 1000 5e468f SecurityAlarm | State: 0, Setting: 5
[info] [client1] RESPONSE: [requester: client1] 1000 70a7bf Lamp | State: 0, Setting: 3
[info] [client1] RESPONSE: [requester: client1] 1001 a6d07c Lamp | State: 0, Setting: 1
[info] [client1] RESPONSE: [requester: client1] 1001 b224cf SecurityAlarm | State: 0, Setting: 4
[info] [client1] RESPONSE: [requester: client1] 1001 df00a1 SecurityAlarm | State: 1, Setting: 3
[info] [client1] RESPONSE: [requester: client1] 1002 5d9abe Thermostat | State: 1, Setting: 67
[info] [client1] RESPONSE: [requester: client1] 1002 283a39 Thermostat | State: 0, Setting: 60
[info] [client1] RESPONSE: [requester: client1] 1002 70b354 SecurityAlarm | State: 0, Setting: 4
[info] [client1] RESPONSE: [requester: client1] 1002 c12ac7 Thermostat | State: 2, Setting: 64
[info] [client1] RESPONSE: [requester: client1] 1003 2587a9 Lamp | State: 0, Setting: 1
[info] [client1] RESPONSE: [requester: client1] 1004 f5732a Thermostat | State: 0, Setting: 63
[info] [client1] REQUEST: 1004 72a5f5 SecurityAlarm | State: 0, Setting: 2
[info] [client1] RESPONSE: [requester: client1] 1004 c7aaf1 Lamp | State: 1, Setting: 2
[info] [client1] REQUEST: 1005 f859d3 Thermostat | State: 2, Setting: 70
[info] [client1] RESPONSE: [requester: client1] 1004 72a5f5 SecurityAlarm | State: 0, Setting: 3
[info] [client1] REQUEST: 1006 4a7da5 SecurityAlarm | State: 0, Setting: 2
[info] [client1] RESPONSE: [requester: client1] 1005 f859d3 Thermostat | State: 0, Setting: 70
[info] [client1] REQUEST: 1006 17ac1a Lamp | State: 0, Setting: 3
[info] [client1] RESPONSE: [requester: client1] 1006 4a7da5 SecurityAlarm | State: 0, Setting: 2
[info] [client1] REQUEST: 1006 58653a Lamp | State: 0, Setting: 2
[info] [client1] RESPONSE: [requester: client1] 1006 17ac1a Lamp | State: 0, Setting: 1
[info] [client1] REQUEST: 1006 0bfa66 SecurityAlarm | State: 1, Setting: 5
[info] [client1] RESPONSE: [requester: client1] 1006 58653a Lamp | State: 0, Setting: 2
[info] [client1] REQUEST: 1007 6caf32 SecurityAlarm | State: 0, Setting: 2
[info] [client1] RESPONSE: [requester: client1] 1006 0bfa66 SecurityAlarm | State: 0, Setting: 2
[info] [client1] REQUEST: 1007 2b67a7 SecurityAlarm | State: 0, Setting: 1
[info] [client1] RESPONSE: [requester: client1] 1007 6caf32 SecurityAlarm | State: 0, Setting: 4
[info] [client1] RESPONSE: [requester: client3] 1040 f237b5 Lamp | State: 1, Setting: 3
[info] [client1] RESPONSE: [requester: client3] 1040 cbeb82 SecurityAlarm | State: 1, Setting: 2
[info] [client1] RESPONSE: [requester: client3] 1040 742dcd Thermostat | State: 1, Setting: 70
[info] [client1] RESPONSE: [requester: client3] 1041 337d19 Lamp | State: 1, Setting: 2
[info] [client1] RESPONSE: [requester: client3] 1041 6d19d6 Thermostat | State: 1, Setting: 64
[info] [client1] RESPONSE: [requester: client3] 1041 144297 Thermostat | State: 0, Setting: 69
[info] [client1] RESPONSE: [requester: client3] 1041 663271 SecurityAlarm | State: 1, Setting: 2
[info] [client1] RESPONSE: [requester: client3] 1042 83807a Lamp | State: 1, Setting: 1
[info] [client1] RESPONSE: [requester: client3] 1042 5ce343 Thermostat | State: 2, Setting: 60
[info] [client1] RESPONSE: [requester: client3] 1042 7ab082 Lamp | State: 1, Setting: 1
[info] [client1] RESPONSE: [requester: client3] 1042 eae803 Thermostat | State: 2, Setting: 65
[info] [client1] REQUEST: 1008 f0c753 Thermostat | State: 2, Setting: 67
[info] [client1] RESPONSE: [requester: client1] 1007 2b67a7 SecurityAlarm | State: 0, Setting: 1
[info] [client1] RESPONSE: [requester: client3] 1043 88ee61 Lamp | State: 0, Setting: 2
[info] [client1] REQUEST: 1008 32ccb2 Lamp | State: 0, Setting: 2
[info] [client1] RESPONSE: [requester: client1] 1008 f0c753 Thermostat | State: 2, Setting: 65
[info] [client1] RESPONSE: [requester: client3] 1043 440b5b Lamp | State: 1, Setting: 3
. . .
. . .
[info] [client1] REQUEST: 1019 3f122b Thermostat | State: 0, Setting: 63
[info] [client1] RESPONSE: [requester: client1] 1019 6f15e0 Lamp | State: 1, Setting: 1
[info] [client1] RESPONSE: [requester: client3] 1055 6a6fde Lamp | State: 0, Setting: 2
[info] [client1] REQUEST: 1019 b8ce7b SecurityAlarm | State: 1, Setting: 5
[info] [client1] RESPONSE: [requester: client1] 1019 3f122b Thermostat | State: 1, Setting: 64
[info] [client1] RESPONSE: [requester: client3] 1056 60eab7 Thermostat | State: 2, Setting: 70
[info] [client1] REQUEST: 1019 93678e SecurityAlarm | State: 0, Setting: 3
[info] [client1] RESPONSE: [requester: client1] 1019 b8ce7b SecurityAlarm | State: 1, Setting: 5
[info] [client1] RESPONSE: [requester: client3] 1056 ae65ad Thermostat | State: 0, Setting: 66
[info] [client1] RESPONSE: [requester: client1] 1019 93678e SecurityAlarm | State: 1, Setting: 4
[info] [client1] RESPONSE: [requester: client3] 1056 cb5d9f Lamp | State: 0, Setting: 1
[info] [client1] RESPONSE: [requester: client3] 1057 c4abf5 Thermostat | State: 0, Setting: 73
[info] [client1] RESPONSE: [requester: client3] 1058 013a30 SecurityAlarm | State: 1, Setting: 5
[info] [client1] RESPONSE: [requester: client3] 1058 681c43 Lamp | State: 1, Setting: 2
[info] [client1] RESPONSE: [requester: client3] 1058 0f1673 Thermostat | State: 1, Setting: 65
[info] [client1] RESPONSE: [requester: client3] 1058 0c97dd Lamp | State: 1, Setting: 3
[info] [client1] RESPONSE: [requester: client3] 1059 e9834d Lamp | State: 1, Setting: 2
[info] [client1] RESPONSE: [requester: client3] 1059 93166b Thermostat | State: 1, Setting: 73

Terminal #3: gRPC Client2 — broadcast OFF (broadcastYN = 0)

% ./sbt "runMain akkagrpc.IotStreamClient client2 0 1020 1039"
[info] welcome to sbt 1.9.6 (Oracle Corporation Java 11.0.19)
[info] loading global plugins from /Users/leo/.sbt/1.0/plugins
[info] loading settings for project akka-grpc-iot-stream-build from plugins.sbt ...
[info] loading project definition from /Users/leo/intellij/akka-grpc-iot-stream/project
[info] loading settings for project akka-grpc-iot-stream from build.sbt ...
[info] set current project to akka-grpc-iot-stream (in build file:/Users/leo/intellij/akka-grpc-iot-stream/)
[info] running (fork) akkagrpc.IotStreamClient client2 0 1020 1039
[info] [2023-10-31 11:53:40,601] [INFO] [akka.event.slf4j.Slf4jLogger] [IotStreamClient-akka.actor.default-dispatcher-3] [] - Slf4jLogger started
[info] Performing streaming requests from client2 ...
[info] [client2] REQUEST: 1020 be1091 Lamp | State: 1, Setting: 3
[info] [client2] REQUEST: 1021 9e6b12 SecurityAlarm | State: 0, Setting: 3
[info] [client2] REQUEST: 1021 cf913c Thermostat | State: 1, Setting: 69
[info] [client2] REQUEST: 1022 4549d2 Lamp | State: 0, Setting: 1
[info] [client2] REQUEST: 1022 08e429 Thermostat | State: 2, Setting: 60
[info] [client2] REQUEST: 1023 aa1eea Lamp | State: 1, Setting: 3
[info] [client2] REQUEST: 1023 af1da0 Thermostat | State: 0, Setting: 70
[info] [client2] REQUEST: 1023 9e7439 Thermostat | State: 0, Setting: 64
[info] [client2] REQUEST: 1023 b21319 SecurityAlarm | State: 0, Setting: 4
[info] [client2] REQUEST: 1024 6ce4c5 SecurityAlarm | State: 1, Setting: 1
[info] [client2] REQUEST: 1024 827653 Thermostat | State: 0, Setting: 64
[info] [client2] REQUEST: 1024 ae359e SecurityAlarm | State: 0, Setting: 1
[info] [client2] RESPONSE: [requester: client2] 1020 be1091 Lamp | State: 0, Setting: 3
[info] [client2] RESPONSE: [requester: client2] 1021 9e6b12 SecurityAlarm | State: 0, Setting: 3
[info] [client2] RESPONSE: [requester: client2] 1021 cf913c Thermostat | State: 1, Setting: 67
[info] [client2] RESPONSE: [requester: client2] 1022 4549d2 Lamp | State: 0, Setting: 3
[info] [client2] RESPONSE: [requester: client2] 1022 08e429 Thermostat | State: 2, Setting: 61
[info] [client2] RESPONSE: [requester: client2] 1023 aa1eea Lamp | State: 1, Setting: 1
[info] [client2] RESPONSE: [requester: client2] 1023 af1da0 Thermostat | State: 2, Setting: 72
[info] [client2] RESPONSE: [requester: client2] 1023 9e7439 Thermostat | State: 2, Setting: 65
[info] [client2] RESPONSE: [requester: client2] 1023 b21319 SecurityAlarm | State: 0, Setting: 3
[info] [client2] RESPONSE: [requester: client2] 1024 6ce4c5 SecurityAlarm | State: 1, Setting: 5
[info] [client2] RESPONSE: [requester: client2] 1024 827653 Thermostat | State: 0, Setting: 64
[info] [client2] REQUEST: 1024 9b4378 Thermostat | State: 1, Setting: 64
[info] [client2] RESPONSE: [requester: client2] 1024 ae359e SecurityAlarm | State: 0, Setting: 1
[info] [client2] REQUEST: 1025 66f837 Lamp | State: 0, Setting: 1
[info] [client2] RESPONSE: [requester: client2] 1024 9b4378 Thermostat | State: 1, Setting: 66
[info] [client2] REQUEST: 1026 b0ac08 SecurityAlarm | State: 1, Setting: 3
[info] [client2] RESPONSE: [requester: client2] 1025 66f837 Lamp | State: 0, Setting: 1
[info] [client2] REQUEST: 1027 249cb9 SecurityAlarm | State: 0, Setting: 5
[info] [client2] RESPONSE: [requester: client2] 1026 b0ac08 SecurityAlarm | State: 0, Setting: 4
[info] [client2] REQUEST: 1027 d205d3 Lamp | State: 1, Setting: 2
[info] [client2] RESPONSE: [requester: client2] 1027 249cb9 SecurityAlarm | State: 0, Setting: 1
[info] [client2] REQUEST: 1027 6783fc Lamp | State: 0, Setting: 1
. . .
. . .
[info] [client2] REQUEST: 1038 af2956 Lamp | State: 0, Setting: 1
[info] [client2] RESPONSE: [requester: client2] 1037 ed954a Lamp | State: 0, Setting: 2
[info] [client2] REQUEST: 1038 656d9f Thermostat | State: 1, Setting: 63
[info] [client2] RESPONSE: [requester: client2] 1038 af2956 Lamp | State: 1, Setting: 3
[info] [client2] REQUEST: 1039 582904 Lamp | State: 1, Setting: 3
[info] [client2] RESPONSE: [requester: client2] 1038 656d9f Thermostat | State: 0, Setting: 62
[info] [client2] REQUEST: 1039 5daf4a SecurityAlarm | State: 0, Setting: 3
[info] [client2] RESPONSE: [requester: client2] 1039 582904 Lamp | State: 1, Setting: 1
[info] [client2] REQUEST: 1039 e31886 Thermostat | State: 1, Setting: 75
[info] [client2] RESPONSE: [requester: client2] 1039 5daf4a SecurityAlarm | State: 1, Setting: 5
[info] [client2] RESPONSE: [requester: client2] 1039 e31886 Thermostat | State: 0, Setting: 75
[info] [client2] Done IoT states streaming.

Terminal #4: gRPC Client3 — broadcast ON (broadcastYN = 1)

% ./sbt "runMain akkagrpc.IotStreamClient client3 1 1040 1059"
[info] welcome to sbt 1.9.6 (Oracle Corporation Java 11.0.19)
[info] loading global plugins from /Users/leo/.sbt/1.0/plugins
[info] loading settings for project akka-grpc-iot-stream-build from plugins.sbt ...
[info] loading project definition from /Users/leo/intellij/akka-grpc-iot-stream/project
[info] loading settings for project akka-grpc-iot-stream from build.sbt ...
[info] set current project to akka-grpc-iot-stream (in build file:/Users/leo/intellij/akka-grpc-iot-stream/)
[info] running (fork) akkagrpc.IotStreamClient client3 1 1040 1059
[info] [2023-10-31 11:53:40,842] [INFO] [akka.event.slf4j.Slf4jLogger] [IotStreamClient-akka.actor.default-dispatcher-3] [] - Slf4jLogger started
[info] Performing streaming requests from client3 ...
[info] [client3] REQUEST: 1040 f237b5 Lamp | State: 0, Setting: 3
[info] [client3] REQUEST: 1040 cbeb82 SecurityAlarm | State: 0, Setting: 2
[info] [client3] REQUEST: 1040 742dcd Thermostat | State: 1, Setting: 72
[info] [client3] REQUEST: 1041 337d19 Lamp | State: 1, Setting: 2
[info] [client3] REQUEST: 1041 6d19d6 Thermostat | State: 1, Setting: 65
[info] [client3] REQUEST: 1041 144297 Thermostat | State: 2, Setting: 68
[info] [client3] REQUEST: 1041 663271 SecurityAlarm | State: 1, Setting: 3
[info] [client3] REQUEST: 1042 83807a Lamp | State: 1, Setting: 2
[info] [client3] REQUEST: 1042 5ce343 Thermostat | State: 0, Setting: 60
[info] [client3] REQUEST: 1042 7ab082 Lamp | State: 1, Setting: 1
[info] [client3] REQUEST: 1042 eae803 Thermostat | State: 0, Setting: 65
[info] [client3] REQUEST: 1043 88ee61 Lamp | State: 1, Setting: 3
[info] [client3] RESPONSE: [requester: client3] 1040 f237b5 Lamp | State: 1, Setting: 3
[info] [client3] RESPONSE: [requester: client3] 1040 cbeb82 SecurityAlarm | State: 1, Setting: 2
[info] [client3] RESPONSE: [requester: client3] 1040 742dcd Thermostat | State: 1, Setting: 70
[info] [client3] RESPONSE: [requester: client3] 1041 337d19 Lamp | State: 1, Setting: 2
[info] [client3] RESPONSE: [requester: client3] 1041 6d19d6 Thermostat | State: 1, Setting: 64
[info] [client3] RESPONSE: [requester: client3] 1041 144297 Thermostat | State: 0, Setting: 69
[info] [client3] RESPONSE: [requester: client3] 1041 663271 SecurityAlarm | State: 1, Setting: 2
[info] [client3] RESPONSE: [requester: client3] 1042 83807a Lamp | State: 1, Setting: 1
[info] [client3] RESPONSE: [requester: client3] 1042 5ce343 Thermostat | State: 2, Setting: 60
[info] [client3] RESPONSE: [requester: client3] 1042 7ab082 Lamp | State: 1, Setting: 1
[info] [client3] RESPONSE: [requester: client3] 1042 eae803 Thermostat | State: 2, Setting: 65
[info] [client3] RESPONSE: [requester: client1] 1007 2b67a7 SecurityAlarm | State: 0, Setting: 1
[info] [client3] REQUEST: 1043 440b5b Lamp | State: 0, Setting: 1
[info] [client3] RESPONSE: [requester: client3] 1043 88ee61 Lamp | State: 0, Setting: 2
[info] [client3] RESPONSE: [requester: client1] 1008 f0c753 Thermostat | State: 2, Setting: 65
[info] [client3] REQUEST: 1043 99c6e0 SecurityAlarm | State: 1, Setting: 1
[info] [client3] RESPONSE: [requester: client3] 1043 440b5b Lamp | State: 1, Setting: 3
[info] [client3] RESPONSE: [requester: client1] 1008 32ccb2 Lamp | State: 0, Setting: 2
[info] [client3] REQUEST: 1044 de863b Lamp | State: 1, Setting: 2
[info] [client3] RESPONSE: [requester: client3] 1043 99c6e0 SecurityAlarm | State: 1, Setting: 5
[info] [client3] RESPONSE: [requester: client1] 1009 edf984 SecurityAlarm | State: 1, Setting: 5
[info] [client3] REQUEST: 1044 04dff8 Lamp | State: 0, Setting: 1
[info] [client3] RESPONSE: [requester: client3] 1044 de863b Lamp | State: 1, Setting: 2
[info] [client3] RESPONSE: [requester: client1] 1009 274bca Thermostat | State: 2, Setting: 68
[info] [client3] REQUEST: 1044 86ed37 SecurityAlarm | State: 1, Setting: 1
[info] [client3] RESPONSE: [requester: client3] 1044 04dff8 Lamp | State: 0, Setting: 1
[info] [client3] RESPONSE: [requester: client1] 1009 50e02f Thermostat | State: 1, Setting: 66
[info] [client3] REQUEST: 1044 fd5984 SecurityAlarm | State: 0, Setting: 3
[info] [client3] RESPONSE: [requester: client3] 1044 86ed37 SecurityAlarm | State: 1, Setting: 5
[info] [client3] RESPONSE: [requester: client1] 1009 c6160b SecurityAlarm | State: 1, Setting: 5
[info] [client3] REQUEST: 1045 a6b326 Thermostat | State: 0, Setting: 60
[info] [client3] RESPONSE: [requester: client3] 1044 fd5984 SecurityAlarm | State: 1, Setting: 1
[info] [client3] RESPONSE: [requester: client1] 1010 eb624d SecurityAlarm | State: 0, Setting: 4
. . .
. . .
[info] [client3] REQUEST: 1057 c4abf5 Thermostat | State: 2, Setting: 73
[info] [client3] RESPONSE: [requester: client3] 1056 cb5d9f Lamp | State: 0, Setting: 1
[info] [client3] REQUEST: 1058 013a30 SecurityAlarm | State: 1, Setting: 5
[info] [client3] RESPONSE: [requester: client3] 1057 c4abf5 Thermostat | State: 0, Setting: 73
[info] [client3] REQUEST: 1058 681c43 Lamp | State: 1, Setting: 3
[info] [client3] RESPONSE: [requester: client3] 1058 013a30 SecurityAlarm | State: 1, Setting: 5
[info] [client3] REQUEST: 1058 0f1673 Thermostat | State: 1, Setting: 64
[info] [client3] RESPONSE: [requester: client3] 1058 681c43 Lamp | State: 1, Setting: 2
[info] [client3] REQUEST: 1058 0c97dd Lamp | State: 1, Setting: 3
[info] [client3] RESPONSE: [requester: client3] 1058 0f1673 Thermostat | State: 1, Setting: 65
[info] [client3] REQUEST: 1059 e9834d Lamp | State: 0, Setting: 2
[info] [client3] RESPONSE: [requester: client3] 1058 0c97dd Lamp | State: 1, Setting: 3
[info] [client3] REQUEST: 1059 93166b Thermostat | State: 0, Setting: 71
[info] [client3] RESPONSE: [requester: client3] 1059 e9834d Lamp | State: 1, Setting: 2
[info] [client3] RESPONSE: [requester: client3] 1059 93166b Thermostat | State: 1, Setting: 73

Akka GRPC for IoT Streams

Borne out of Google and open-sourced in 2015, gRPC is a RPC framework which has been increasingly talked about over the past few years. In case you’re curious about what the g in gRPC stands for, it turns out the the term is a peculiar recursive acronym of gRPC Remote Procedure Calls.

gRPC uses Protocol Buffers for serialization and as its IDL (Interface Definition Language). It also relies on HTTP/2 as its transport. While HTTP/2 has been growing in demand, its adoption rate is still rather slow. As of this writing, only slightly over 1/3 of websites support HTTP/2. That inevitably slows down gRPC’s adoption. Nevertheless, it’s hard to ignore the goodies it offers. In particular, gRPC has been known for its strength for building systems that demand a microservices design with fast inter-service calls with de-coupled interfaces across polyglot services. A comprehensive list of its benefits is available in this Akka gRPC tech doc section.

Akka gRPC

Operating on top of Akka Streams and Akka HTTP, Akka gRPC provides support for building streaming gRPC servers and clients.

On the server side, Akka gRPC generates service interfaces (as Scala traits) based on the individual services defined in the Protobuf schema. The server-side programming logic can then be crafted as specific service implementations. Akka gRPC also generates from the Protobuf services definition a number of service handlers that take the service implementation as an input parameter and return a HttpRequest => Future[HttpResponse] route in Akka-HTTP.

As for the client side, a client program would use the service stubs generated by Akka gRPC (through implementing the service interfaces) to invoke the remote services. The following diagram highlights what a streaming gRPC server and clients might look like.

Akka gRPC Streaming

IoT systems of sensor devices

In many use cases, an IoT (Internet of Things) system of sensor devices consists of a large amount of devices running on some LAN/WiFi or wireless personal area networks (WPAN). A previous blog post of mine re: running IoT sensor devices using Akka’s distributed pub/sub in Scala illustrates how an Akka Actor-based cluster fits into managing large-scale interactive IoT devices.

This time, rather than centering the IoT system around an actor model, we’re going to implement the system using Akka gRPC in Scala, leveraging the robust Akka Streams API applied in accordance with the Protobuf services definition and running on an HTTP/2 compliant server.

A simple use case

We’ll start with a simple use case. Let’s say we have an optimization algorithm running on a server that analyzes current operational states of a given IoT sensor device (e.g. a thermostat) and returns revised states.

On the client side, there can be many clients, each handles the sensor devices for a specific group of real estate properties. Each client application would submit to the server the current operational states and settings of the devices, as a stream of state-update requests.

The server would then run of the optimization algorithm based on each device’s current state and setting and the property it’s in to return an object with revised state and setting, as an element of the response stream. In this use case, the response stream will be received by the same client firing off the request stream.

Each device has the following attributes:

  • deviceType:
    • 0 = Thermostat
    • 1 = Lamp
    • 2 = SecurityAlarm
  • opState:
    • devType 0 => 0 | 1 | 2 (OFF | HEAT | COOL)
    • devType 1 => 0 | 1 (OFF | ON)
    • devType 2 => 0 | 1 (OFF | ON)
  • setting:
    • devType 0 => 60 – 75
    • devType 1 => 1 – 3
    • devType 2 => 1 – 5

A slightly more complex use case that involves dynamically broadcasting response streams from the server to participating clients will be discussed in a subsequent blog post.

Library dependencies

Using sbt as the build tool, build.sbt would look like this:

name := "akka-grpc-iot-stream"

version := "1.0"

scalaVersion := "2.13.4"

lazy val akkaVersion = "2.8.5"
lazy val akkaHttpVersion = "10.5.2"
lazy val akkaGrpcVersion = "2.3.4"

enablePlugins(AkkaGrpcPlugin)

fork := true

libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-http" % akkaHttpVersion,
  "com.typesafe.akka" %% "akka-http2-support" % akkaHttpVersion,
  "com.typesafe.akka" %% "akka-actor-typed" % akkaVersion,
  "com.typesafe.akka" %% "akka-stream" % akkaVersion,
  "com.typesafe.akka" %% "akka-discovery" % akkaVersion,
  "com.typesafe.akka" %% "akka-pki" % akkaVersion,

  "com.typesafe.akka" %% "akka-http" % akkaHttpVersion,
  "com.typesafe.akka" %% "akka-http2-support" % akkaHttpVersion,

  "ch.qos.logback" % "logback-classic" % "1.2.3"
)

Note that AkkaGrpcPlugin is the plug-in that carries out all the gRPC generator functions with akka-http2-support ensuring the necessary HTTP/2 support for gRPC.

The IotDevice class

First, we come up with the IotDevice class that represents our IoT sensor devices. For illustration purpose, we add a withRandomStates() method within the companion object for creating an IotDevice object initialized with random states.

object DeviceType extends Enumeration {
  type DeviceType = Value
  val Thermostat: Value = Value(0)
  val Lamp: Value = Value(1)
  val SecurityAlarm: Value = Value(2)
}

case class IotDevice( deviceId: String,
                      deviceType: Int,
                      propertyId: Int,
                      timestamp: Long,
                      opState: Int,
                      setting: Int )

object IotDevice {

  def withRandomStates(propertyId: Int): IotDevice = {
    val devType = randomInt(0, 3)  // 0 -> Thermostat | 1 -> Lamp | 2 -> SecurityAlarm
    val (opState: Int, setting: Int) = devType match {
      case 0 => (randomInt(0, 3), randomInt(60, 76))  // 0|1|2 (OFF|HEAT|COOL), 60-75
      case 1 => (randomInt(0, 2), randomInt(1, 4))  // 0|1 (OFF|ON), 1-3
      case 2 => (randomInt(0, 2), randomInt(1, 6))  // 0|1 (OFF|ON), 1-5
    }
    IotDevice(
      randomId(),
      devType,
      propertyId,
      System.currentTimeMillis(),
      opState,
      setting
    )
  }
}

Protobuf schema

Next, we define our request/response messages and RPC services in file src/main/protobuf/iotstream.proto:

syntax = "proto3";

option java_multiple_files = true;
option java_package = "akkagrpc";
option java_outer_classname = "IotStreamProto";

service IotStreamService {
    rpc sendIotUpdate(stream StatesUpdateRequest) returns (stream StatesUpdateResponse) {}
}

message StatesUpdateRequest {
    string id = 1;
    string client_id = 2;
    int32 property_id = 3;
    string device_id = 4;
    int32 device_type = 5;
    int64 timestamp = 6;
    int32 op_state = 7;
    int32 setting = 8;
}

message StatesUpdateResponse {
    string id = 1;
    string client_id = 2;
    int32 property_id = 3;
    string device_id = 4;
    int32 device_type = 5;
    int64 timestamp = 6;
    int32 op_state_new = 7;
    int32 setting_new = 8;
}

As shown in the Protobuf schema, messages StatesUpdateRequest and StatesUpdateResponse define the request and response streams for the gRPC application, whereas service IotStreamService reveals the signature of the RPC service, leaving its business logic in be implemented in Scala code.

Classes generated by Akka gRPC

The AkkaGrpcPlugin automatically generates Scala source code equivalent to the defined Protobuf messages and to-be-implemented RPC services as Scala traits and classes, along with Akka Stream flows and Akka HTTP routes. The generated classes are placed under target/scala-<scalaVersion>/akka-grpc/main/akkagrpc/:

  • IotstreamProto.scala
  • IotStreamService.scala
  • IotStreamServiceHandler.scala
  • IotStreamServiceClient.scala
  • StatesUpdateRequest.scala
  • StatesUpdateResponse.scala

Service implementation

Now that the generated service interfaces and handlers are in place, we’re ready to create our specific service implementation as class IotStreamServiceImpl:

package akkagrpc

import akka.NotUsed
import akka.actor.typed.ActorSystem
import akka.stream.scaladsl._
import scala.concurrent.duration._
import java.util.UUID
import java.util.concurrent.ThreadLocalRandom

class IotStreamServiceImpl(system: ActorSystem[_]) extends IotStreamService {

  private implicit val sys: ActorSystem[_] = system

  val backpressureTMO: FiniteDuration = 3.seconds

  val updateIotFlow: Flow[StatesUpdateRequest, StatesUpdateResponse, NotUsed] =
    Flow[StatesUpdateRequest]
      .map { case StatesUpdateRequest(id, clientId, propId, devId, devType, ts, opState, setting, _) =>
        val (opStateNew, settingNew) =
          updateDeviceStates(propId, devId, devType, opState, setting)
        StatesUpdateResponse(
          randomId(),
          clientId,
          propId,
          devId,
          devType,
          System.currentTimeMillis(),
          opStateNew,
          settingNew)
        }

  @Override
  def sendIotUpdate(requests: Source[StatesUpdateRequest, NotUsed]): Source[StatesUpdateResponse, NotUsed] =
    requests.via(updateIotFlow).backpressureTimeout(backpressureTMO)

  def updateDeviceStates(propId: Int, devId: String, devType: Int, opState: Int, setting: Int): (Int, Int) = {
    // Random device states update simulating algorithmic adjustment in accordance with device and
    // property specific factors (temperature, lighting, etc)
    devType match {
      case 0 =>
        val opStateNew =
          if (opState == 0) randomInt(0, 3) else {
            if (opState == 1) randomInt(0, 2) else (2 + randomInt(0, 2)) % 3
          }
        val settingTemp = setting + randomInt(-2, 3)
        val settingNew = if (settingTemp < 60) 60 else if (settingTemp > 75) 75 else settingTemp
        (opStateNew, settingNew)
      case 1 =>
        (randomInt(0, 2), randomInt(1, 4))
      case 2 =>
        (randomInt(0, 2), randomInt(1, 6))
    }
  }

  def randomInt(a: Int, b: Int): Int = ThreadLocalRandom.current().nextInt(a, b)

  def randomId(): String = UUID.randomUUID().toString.slice(0, 6)  // UUID's first 6 chars
}

Encapsulating the device states update simulation logic, the Akka Stream flow updateIotFlow creates the stream to be carried out by the sendIotUpdate() RPC — all handled by Akka gRPC behind the scene.

TLS-enabled HTTP/2 server

For a skeletal HTTP/2 compliant server, we create class IotStreamServer by borrowing part of the GreeterService sample code available at Lightbend developers guide.

package akkagrpc

import java.security.{KeyStore, SecureRandom}
import java.security.cert.{Certificate, CertificateFactory}

import akka.actor.typed.ActorSystem
import akka.actor.typed.scaladsl.Behaviors
import akka.http.scaladsl.{ConnectionContext, Http, HttpsConnectionContext}
import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
import akka.pki.pem.{DERPrivateKeyLoader, PEMDecoder}
import com.typesafe.config.ConfigFactory
import javax.net.ssl.{KeyManagerFactory, SSLContext}

import scala.concurrent.{ExecutionContext, Future}
import scala.concurrent.duration._
import scala.util.{Success, Failure}
import scala.io.Source

object IotStreamServer {

  def main(args: Array[String]): Unit = {
    // important to enable HTTP/2 in ActorSystem's config
    val conf = ConfigFactory.parseString("akka.http.server.preview.enable-http2 = on")
      .withFallback(ConfigFactory.defaultApplication())
    val system = ActorSystem[Nothing](Behaviors.empty, "IotStreamServer", conf)
    new IotStreamServer(system).run()
  }
}

class IotStreamServer(system: ActorSystem[_]) {

  def run(): Future[Http.ServerBinding] = {
    implicit val sys = system
    implicit val ec: ExecutionContext = system.executionContext

    val service: HttpRequest => Future[HttpResponse] =
      IotStreamServiceHandler(new IotStreamServiceImpl(system))

    val boundServer: Future[Http.ServerBinding] = Http(system)
      .newServerAt(interface = "127.0.0.1", port = 8080)
      .enableHttps(serverHttpContext)
      .bind(service)
      .map(_.addToCoordinatedShutdown(hardTerminationDeadline = 10.seconds))

    boundServer.onComplete {
      case Success(binding) =>
        val address = binding.localAddress
        Console.out.println(s"[Server] gRPC server bound to ${address.getHostString}:${address.getPort}")
      case Failure(ex) =>
        Console.err.println("[Server] ERROR: Failed to bind gRPC endpoint, terminating system ", ex)
        system.terminate()
    }

    boundServer
  }

  private def serverHttpContext: HttpsConnectionContext = {
    val privateKey =
      DERPrivateKeyLoader.load(PEMDecoder.decode(readPrivateKeyPem()))
    val fact = CertificateFactory.getInstance("X.509")
    val cer = fact.generateCertificate(
      classOf[IotStreamServer].getResourceAsStream("/certs/server1.pem")
    )
    val ks = KeyStore.getInstance("PKCS12")
    ks.load(null)
    ks.setKeyEntry(
      "private",
      privateKey,
      new Array[Char](0),
      Array[Certificate](cer)
    )
    val keyManagerFactory = KeyManagerFactory.getInstance("SunX509")
    keyManagerFactory.init(ks, null)
    val context = SSLContext.getInstance("TLS")
    context.init(keyManagerFactory.getKeyManagers, null, new SecureRandom)
    ConnectionContext.httpsServer(context)
  }

  private def readPrivateKeyPem(): String =
    Source.fromResource("certs/server1.key").mkString
}

For development purposes, contrary to just having a self-signed PKCS#12 certificate for a TLS-enabled HTTP server, gRPC clients have more stringent requirement, demanding a HTTP server certificate along with a valid Certificate Authority (CA) certificate that signs the server cert. Rather than going through the process of creating our own CA, for just demonstration purpose, we use the CA certificate that comes with the GreeterService code. The host, port number along with the CA certificate file path are configured for the gRPC client within application.conf, which has content like below:

akka.grpc.client {
  "akkagrpc.IotStreamService" {
    host = 127.0.0.1
    port = 8080
    override-authority = foo.test.google.fr
    trusted = /certs/ca.pem
  }
}

The client application

As shown in the source code of IotStreamClient, the client app passes a stream of states update requests from a group of real estate properties as parameters to method sendIotUpdate() in the gRPC stub IotStreamServiceClient generated by Akka gRPC.

package akkagrpc

import akka.{Done, NotUsed}
import akka.actor.typed.ActorSystem
import akka.actor.typed.scaladsl.Behaviors
import akka.grpc.GrpcClientSettings
import akka.stream.scaladsl.Source
import akka.stream.ThrottleMode.Shaping

import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Failure, Success, Try}
import scala.concurrent.duration._

import Util._

// akkagrpc.IotStreamClient clientId propIdStart propIdEnd
//   e.g. akkagrpc.IotStreamClient client1 1000 1049
object IotStreamClient {

  def getDevicesByProperty(propId: Int): Iterator[IotDevice] =
    (1 to randomInt(1, 5)).map { _ =>  // 1-4 devices per property
        IotDevice.withRandomStates(propId)
      }.iterator

  def main(args: Array[String]): Unit = {
    implicit val sys: ActorSystem[_] = ActorSystem(Behaviors.empty, "IotStreamClient")
    implicit val ec: ExecutionContext = sys.executionContext

    val client = IotStreamServiceClient(GrpcClientSettings.fromConfig("akkagrpc.IotStreamService"))

    val (clientId: String, broadcastYN: Int, propIdStart: Int, propIdEnd: Int) =
      if (args.length == 3) {
        Try((args(0), args(1).toInt, args(2).toInt) match {
          case Success((cid, pid1, pid2)) =>
            (cid, pid1, pid2)
          case _ =>
            Console.err.println("[Main] ERROR: Arguments required: clientId, propIdStart & propIdEnd  e.g. client1 1000 1049")
            System.exit(1)
        }
      }
      else
        ("client1", 1000, 1029)  // Default clientId & property id range (inclusive)

    val devices: Iterator[IotDevice] =
      (propIdStart to propIdEnd).flatMap(getDevicesByProperty).iterator

    Console.out.println(s"Performing streaming requests from $clientId ...")
    grpcStreaming(clientId)

    def grpcStreaming(clientId: String): Unit = {
      val requestStream: Source[StatesUpdateRequest, NotUsed] =
        Source
          .fromIterator(() => devices)
          .map { case IotDevice(devId, devType, propId, ts, opState, setting) =>
            Console.out.println(s"[$clientId] REQUEST: $propId $devId ${DeviceType(devType)} | State: $opState, Setting: $setting")
            StatesUpdateRequest(randomId(), clientId, propId, devId, devType, ts, opState, setting)
          }
          .throttle(1, 100.millis, 10, Shaping)  // For illustration only

      val responseStream: Source[StatesUpdateResponse, NotUsed] = client.sendIotUpdate(requestStream)

      val done: Future[Done] =
        responseStream.runForeach {
          case StatesUpdateResponse(id, clntId, propId, devId, devType, ts, opState, setting, _) =>
            Console.out.println(s"[$clientId] RESPONSE: [requester: $clntId] $propId $devId ${DeviceType(devType)} | State: $opState, Setting: $setting")
        }

      done.onComplete {
        case Success(_) =>
          Console.out.println(s"[$clientId] Done IoT states streaming.")
        case Failure(e) =>
          Console.err.println(s"[$clientId] ERROR: $e")
      }

      Thread.sleep(2000)
    }
  }
}

Running the applications

To run the server application, open a command line terminal and run as follows:

# On terminal #1
cd <project-root>
sbt "runMain akkagrpc.IotStreamServer"

For the client application, open a terminal for each client to run a specific range of IDs of real estate properties:

# On terminal #2
cd <project-root>
sbt "runMain akkagrpc.IotStreamClient client1 1000 1019"

# On terminal #3
cd <project-root>
sbt "runMain akkagrpc.IotStreamClient client2 1020 1039"

Below are sample output of the gRPC server and a couple of clients.

Terminal #1: gRPC Server

% ./sbt "runMain akkagrpc.IotStreamServer"
[info] compiling ...
[info] done compiling
[info] running (fork) akkagrpc.IotStreamServer 
[info] [2023-10-23 11:36:53,173] [INFO] [akka.event.slf4j.Slf4jLogger] [IotStreamServer-akka.actor.default-dispatcher-3] [] - Slf4jLogger started
[info] [Server] gRPC server bound to 127.0.0.1:8080

Terminal #2: gRPC Client1

% ./sbt "runMain akkagrpc.IotStreamClient client1 1000 1019"
[info] welcome to sbt 1.9.6 (Oracle Corporation Java 11.0.19)
[info] loading global plugins from /Users/leo/.sbt/1.0/plugins
[info] loading settings for project akka-grpc-iot-stream-build from plugins.sbt ...
[info] loading project definition from /Users/leo/intellij/akka-grpc-iot-stream/project
[info] loading settings for project akka-grpc-iot-stream from build.sbt ...
[info] set current project to akka-grpc-iot-stream (in build file:/Users/leo/intellij/akka-grpc-iot-stream/)
[info] running (fork) akkagrpc.IotStreamClient client1 0 1000 1019
[info] [2023-10-18 11:37:19,401] [INFO] [akka.event.slf4j.Slf4jLogger] [IotStreamClient-akka.actor.default-dispatcher-4] [] - Slf4jLogger started
[info] Performing streaming requests from client1 ...
[info] [client1] REQUEST: 1000 76a2cb Thermostat | State: 1, Setting: 65
[info] [client1] REQUEST: 1001 6588b0 SecurityAlarm | State: 0, Setting: 3
[info] [client1] REQUEST: 1001 2f9150 Lamp | State: 0, Setting: 3
[info] [client1] REQUEST: 1001 a33bd1 SecurityAlarm | State: 0, Setting: 2
[info] [client1] REQUEST: 1001 eabc4b SecurityAlarm | State: 1, Setting: 4
[info] [client1] REQUEST: 1002 c57009 Thermostat | State: 1, Setting: 70
[info] [client1] REQUEST: 1003 4a038c Lamp | State: 0, Setting: 2
[info] [client1] REQUEST: 1003 06bc8b Thermostat | State: 1, Setting: 65
[info] [client1] REQUEST: 1004 ad9432 Lamp | State: 1, Setting: 3
[info] [client1] REQUEST: 1004 356ef0 Lamp | State: 1, Setting: 1
[info] [client1] REQUEST: 1004 f12061 Thermostat | State: 2, Setting: 61
[info] [client1] REQUEST: 1004 983c20 Lamp | State: 0, Setting: 1
[info] [client1] REQUEST: 1005 087963 SecurityAlarm | State: 1, Setting: 3
[info] [client1] RESPONSE: [requester: client1] 1000 76a2cb Thermostat | State: 1, Setting: 63
[info] [client1] RESPONSE: [requester: client1] 1001 6588b0 SecurityAlarm | State: 1, Setting: 1
[info] [client1] RESPONSE: [requester: client1] 1001 2f9150 Lamp | State: 0, Setting: 3
[info] [client1] RESPONSE: [requester: client1] 1001 a33bd1 SecurityAlarm | State: 1, Setting: 3
[info] [client1] RESPONSE: [requester: client1] 1001 eabc4b SecurityAlarm | State: 0, Setting: 1
. . .
. . .
[info] [client1] REQUEST: 1019 799659 Lamp | State: 1, Setting: 3
[info] [client1] RESPONSE: [requester: client1] 1019 194f79 Thermostat | State: 2, Setting: 63
[info] [client1] REQUEST: 1019 cbdf82 Thermostat | State: 0, Setting: 66
[info] [client1] RESPONSE: [requester: client1] 1019 799659 Lamp | State: 1, Setting: 3
[info] [client1] REQUEST: 1019 76307e SecurityAlarm | State: 1, Setting: 1
[info] [client1] RESPONSE: [requester: client1] 1019 cbdf82 Thermostat | State: 0, Setting: 64
[info] [client1] RESPONSE: [requester: client1] 1019 76307e SecurityAlarm | State: 0, Setting: 4
[info] [client1] Done IoT states streaming.

Terminal #3: gRPC Client2

% ./sbt "runMain akkagrpc.IotStreamClient client2 1020 1039"
[info] welcome to sbt 1.9.6 (Oracle Corporation Java 11.0.19)
[info] loading global plugins from /Users/leo/.sbt/1.0/plugins
[info] loading settings for project akka-grpc-iot-stream-build from plugins.sbt ...
[info] loading project definition from /Users/leo/intellij/akka-grpc-iot-stream/project
[info] loading settings for project akka-grpc-iot-stream from build.sbt ...
[info] set current project to akka-grpc-iot-stream (in build file:/Users/leo/intellij/akka-grpc-iot-stream/)
[info] running (fork) akkagrpc.IotStreamClient client2 0 1020 1039
[info] [2023-10-18 11:37:19,401] [INFO] [akka.event.slf4j.Slf4jLogger] [IotStreamClient-akka.actor.default-dispatcher-3] [] - Slf4jLogger started
[info] Performing streaming requests from client2 ...
[info] [client2] REQUEST: 1020 2cb5a8 Thermostat | State: 0, Setting: 71
[info] [client2] REQUEST: 1020 1a6b0e Lamp | State: 1, Setting: 3
[info] [client2] REQUEST: 1020 d1bd73 Thermostat | State: 2, Setting: 60
[info] [client2] REQUEST: 1020 5d9f65 Thermostat | State: 0, Setting: 69
[info] [client2] REQUEST: 1021 711d17 Lamp | State: 1, Setting: 2
[info] [client2] REQUEST: 1021 443245 Thermostat | State: 2, Setting: 73
[info] [client2] REQUEST: 1022 16fff9 Lamp | State: 0, Setting: 2
[info] [client2] REQUEST: 1022 687826 Lamp | State: 0, Setting: 3
[info] [client2] REQUEST: 1022 2cae5f SecurityAlarm | State: 0, Setting: 1
[info] [client2] REQUEST: 1022 c9e8f9 Thermostat | State: 1, Setting: 69
[info] [client2] REQUEST: 1023 6984f2 Lamp | State: 1, Setting: 2
[info] [client2] REQUEST: 1024 a85495 Thermostat | State: 2, Setting: 72
[info] [client2] RESPONSE: [requester: client2] 1020 2cb5a8 Thermostat | State: 0, Setting: 71
[info] [client2] RESPONSE: [requester: client2] 1020 1a6b0e Lamp | State: 0, Setting: 1
[info] [client2] RESPONSE: [requester: client2] 1020 d1bd73 Thermostat | State: 0, Setting: 61
[info] [client2] RESPONSE: [requester: client2] 1020 5d9f65 Thermostat | State: 2, Setting: 67
[info] [client2] RESPONSE: [requester: client2] 1021 711d17 Lamp | State: 0, Setting: 1
. . .
. . .
[info] [client2] REQUEST: 1038 a03d22 Thermostat | State: 2, Setting: 68
[info] [client2] RESPONSE: [requester: client2] 1038 c02238 Lamp | State: 1, Setting: 1
[info] [client2] REQUEST: 1038 9e6d4b Thermostat | State: 0, Setting: 72
[info] [client2] RESPONSE: [requester: client2] 1038 a03d22 Thermostat | State: 0, Setting: 67
[info] [client2] REQUEST: 1039 3d7e6d SecurityAlarm | State: 1, Setting: 3
[info] [client2] RESPONSE: [requester: client2] 1038 9e6d4b Thermostat | State: 2, Setting: 74
[info] [client2] RESPONSE: [requester: client2] 1039 3d7e6d SecurityAlarm | State: 1, Setting: 2
[info] [client2] Done IoT states streaming.

What’s next?

In the next blog post, we’ll go over a use case in which the states update request streams from the various clients will be processed by a gRPC dynamic pub/sub service with the response streams broadcast to be consumed by all the participating clients. Source code that includes both use cases will be published in a GitHub repo.

A Rate-limiter In Akka Stream

Rate-limiting is a common measure for preventing the resource of a given computing service (e.g. an API service) from being swamped by excessive requests. There are various strategies for achieving rate-limiting, but fundamentally it’s about how to limit the frequency of requests from any sources within a set time window. While a rate-limiter can be implemented in many different ways, it’s, by nature, something well-positioned to be crafted as a stream operator.

Wouldn’t “throttle()” suffice?

Akka Stream’s versatile stream processing functions make it an appealing option for implementing rate-limiters. It provides stream operators like throttle() with token bucket model for industry-standard rate-limiting. However, directly applying the function to the incoming request elements would mechanically throttle every request, thus “penalizing” requests from all sources when excessive requests were from, say, just a single source.

We need a slightly more sophisticated rate-limiting solution for the computing service to efficiently serve “behaving” callers while not being swamped by “misbehaving” ones.

Rate-limiting calls to an API service

Let’s say we have an API service that we would like to equip with rate-limiting. Incoming requests will be coming through as elements of an input stream. Each incoming request will consist of source-identifying and API-call, represented as a simple case class instance with apiKey being the unique key/id for an API user and apiParam the submitted parameter for the API call:

case class Request[A](apiKey: String, apiParam: A)

A simplistic API call function that takes the apiKey, apiParam and returns a Future may look something like this:

def apiCall[A, B](key: String, param: A)(implicit ec: ExecutionContext): Future[B] = ???

For illustration purpose, we’ll trivialize it to return a String-type Future:

def apiCall[A](key: String, param: A)(implicit ec: ExecutionContext): Future[String] =
  Future{s"apiResult($key, $param)"}

Next, we define the following main attributes for the rate-limiter:

val timeWindow = 2.seconds
val maxReqs = 10       // Max overall requests within the timeWindow
val maxReqsPerKey = 3  // Max requests per apiKey within the timeWindow

Strategy #1: Discard excessive API calls from any sources

We’ll look into two different filtering strategies that rate-limit calls to our API service. One approach is to limit API calls within the predefined timeWindow from any given apiKey to not more than the maxReqsPerKey value. In other words, those excessive incoming requests with a given apiKey above the maxReqsPerKey limit will be discarded. We can come up with such filtering logic as a FlowShape like below:

// Rate-limiting flow that discards excessive API calls from any sources
def keepToLimitPerKey[A](): Flow[Seq[Request[A]], Seq[Request[A]], akka.NotUsed] = Flow[Seq[Request[A]]].
  map{ g =>
    g.foldLeft((List.empty[Request[A]], Map.empty[String, Int])){ case ((acc, m), req) =>
      val count = m.getOrElse(req.apiKey, 0) + 1
      if (count <= maxReqsPerKey) (req :: acc, m + (req.apiKey -> count))
      else (acc, m + (req.apiKey -> count))
    }._1.toSeq.reverse
  }

The filtering Flow takes a sequence of requests returns a filtered sequence. By iterating through the input sequence with foldLeft while keeping track of the request count per apiKey with a Map, it keeps only up to the first maxReqsPerKey of requests for any given apiKey.

Strategy #2: Drop all API calls from any “offending” sources

An alternative strategy is that for any given apiKey, all API calls with the key will be dropped if the count exceeds the maxReqsPerKey value within the timeWindow. Here’s the corresponding filtering Flow:

// Rate-limiting flow that drops all API calls from any offending sources
def dropAllReqsByKey[A](): Flow[Seq[Request[A]], Seq[Request[A]], akka.NotUsed] = Flow[Seq[Request[A]]].
  map{ g =>
    val offendingKeys = g.groupMapReduce(_.apiKey)(_ => 1)(_ + _).
      collect{ case (key, cnt) if cnt > maxReqsPerKey => key }.toSeq
    g.filterNot(req => offendingKeys.contains(req.apiKey))
  }

As shown in the self-explanatory code, this alternative filtering Flow simply identifies which apiKeys originate the count-violating requests per timeWindow and filter out all of their requests.

Grouping API requests in time windows using “groupedWithin()”

Now that we’re equipped with a couple of rate-limiting strategies, we’re going to come up with a stream operator that does the appropriate grouping of the API requests. To achieve that, we use Akka Stream function groupedWithin() which divides up a stream into groups of up to a given number of elements received within a time window. It has the following method signature:

def groupedWithin(n: Int, d: FiniteDuration): Repr[Seq[Out]]

The function produces chunks of API requests that serve as properly-typed input to be ingested by one of the filtering Flows we’ve created. That seems to fit perfectly into what we need.

Well, there is a caveat though. The groupedWithin() operator emits when the given time interval (i.e. d, which corresponds to timeWindow in our use case) elapses since the previous emission or the specified number of elements (i.e. n, which corresponds to our maxReqs) is buffered — whichever happens first. In essence, if there are more than n elements readily available upstream, the operator will not fulfill our at-most n elements requirement within the time window.

A work-around is to subsequently apply the throttle() to the grouped requests as a single batch to enforce the time-windowed rate-limiting requirement.

Test-running our API service rate-limiter

Let’s assemble a minuscule stream of requests to test-run our rate-limiter using the first filtering strategy. To make it easy to spot the dropped API requests, we assign the apiParam parameter of each request an integer value that reveals the request’ position in the input stream via zipWithIndex.

import akka.actor.ActorSystem
import akka.stream.scaladsl._
import akka.stream.{ActorMaterializer, ThrottleMode, OverflowStrategy}
import akka.NotUsed
import scala.concurrent.{ExecutionContext, Future}
import scala.concurrent.duration._

implicit val system = ActorSystem("system")
implicit val ec = system.dispatcher
implicit val materializer = ActorMaterializer()  // for Akka stream v2.5 or below

case class Request[A](apiKey: String, apiParam: A)

def apiCall[A](key: String, param: A)(implicit ec: ExecutionContext): Future[String] =
  Future{s"apiResult($key, $param)"}

val timeWindow = 2.seconds
val maxReqs = 10
val maxReqsPerKey = 3

val requests: Iterator[Request[Int]] = Vector(
    5, 1, 1, 4, 5, 5, 5, 6, 2, 2,  // Rogue keys: `5`
    1, 5, 5, 2, 3, 4, 6, 6, 4, 4,
    5, 4, 3, 3, 4, 4, 4, 1, 3, 3,  // Rogue keys: `3` & `4` 
    6, 1, 1, 4, 4, 1, 1, 5         // Rogue keys: `1`
  ).
  zipWithIndex.
  map{ case (x, i) => Request(s"k-$x", i + 1) }.
  iterator

Source.fromIterator(() => requests).
  groupedWithin(maxReqs, timeWindow).
  via(keepToLimitPerKey()).  // Rate-limiting strategy #1
  throttle(1, timeWindow, 1, ThrottleMode.Shaping).
  mapConcat(_.map(req => apiCall(req.apiKey, req.apiParam))).
  runForeach(println)

| Future(Success(apiResult(k-5, 1)))
| Future(Success(apiResult(k-1, 2)))
| Future(Success(apiResult(k-1, 3)))
| Future(Success(apiResult(k-4, 4)))
| Future(Success(apiResult(k-5, 5)))
| Future(Success(apiResult(k-5, 6)))   // Request(k-5, 7) dropped
| Future(Success(apiResult(k-6, 8)))
| Future(Success(apiResult(k-2, 9)))
| Future(Success(apiResult(k-2, 10)))
v <-- ~2 seconds
| Future(Success(apiResult(k-1, 11)))
| Future(Success(apiResult(k-5, 12)))
| Future(Success(apiResult(k-5, 13)))
| Future(Success(apiResult(k-2, 14)))
| Future(Success(apiResult(k-3, 15)))
| Future(Success(apiResult(k-4, 16)))
| Future(Success(apiResult(k-6, 17)))
| Future(<not completed>)
| Future(<not completed>)
| Future(Success(apiResult(k-4, 20)))
v <-- ~2 seconds
| Future(Success(apiResult(k-5, 21)))
| Future(Success(apiResult(k-4, 22)))
| Future(Success(apiResult(k-3, 23)))
| Future(Success(apiResult(k-3, 24)))
| Future(Success(apiResult(k-4, 25)))
| Future(Success(apiResult(k-4, 26)))  // Request(k-4, 27) dropped
| Future(Success(apiResult(k-1, 28)))
| Future(Success(apiResult(k-3, 29)))  // Request(k-3, 30) dropped
v <-- ~2 seconds
| Future(<not completed>)
| Future(Success(apiResult(k-1, 32)))
| Future(Success(apiResult(k-1, 33)))
| Future(Success(apiResult(k-4, 34)))
| Future(Success(apiResult(k-4, 35)))
| Future(Success(apiResult(k-1, 36)))  // Request(k-1, 37) dropped
| Future(Success(apiResult(k-5, 38)))
v <-- ~2 seconds

Note that mapConcat() is for flattening the stream of grouped API requests back to a stream of individual requests in their original order.

Next, we test-run our rate-limiter using the alternative filtering strategy with the same input stream and timeWindow/maxReqs/maxReqsPerKey parameters:

val requests: Iterator[Request[Int]] = Vector(
    5, 1, 1, 4, 5, 5, 5, 6, 2, 2,  // Rogue keys: `5`
    1, 5, 5, 2, 3, 4, 6, 6, 4, 4,
    5, 4, 3, 3, 4, 4, 4, 1, 3, 3,  // Rogue keys: `3` & `4` 
    6, 1, 1, 4, 4, 1, 1, 5         // Rogue keys: `1`
  ).
  zipWithIndex.
  map{ case (x, i) => Request(s"k-$x", i + 1) }.
  iterator

Source.fromIterator(() => requests).
  groupedWithin(maxReqs, timeWindow).
  via(dropAllReqsByKey()).  // Rate-limiting strategy #2
  throttle(1, timeWindow, 1, ThrottleMode.Shaping).
  mapConcat(_.map(req => apiCall(req.apiKey, req.apiParam))).
  runForeach(println)

| Future(Success(apiResult(k-1, 2)))
| Future(<not completed>)
| Future(Success(apiResult(k-4, 4)))
| Future(Success(apiResult(k-6, 8)))
| Future(Success(apiResult(k-2, 9)))
| Future(Success(apiResult(k-2, 10)))  // All requests by k-5 dropped
v <-- ~2 seconds
| Future(<not completed>)
| Future(Success(apiResult(k-5, 12)))
| Future(Success(apiResult(k-5, 13)))
| Future(Success(apiResult(k-2, 14)))
| Future(Success(apiResult(k-3, 15)))
| Future(Success(apiResult(k-4, 16)))
| Future(Success(apiResult(k-6, 17)))
| Future(Success(apiResult(k-6, 18)))
| Future(Success(apiResult(k-4, 19)))
| Future(Success(apiResult(k-4, 20)))
v <-- ~2 seconds
| Future(Success(apiResult(k-5, 21)))
| Future(Success(apiResult(k-1, 28)))  // All requests by k-3 or k-4 dropped
v <-- ~2 seconds
| Future(Success(apiResult(k-6, 31)))
| Future(Success(apiResult(k-4, 34)))
| Future(Success(apiResult(k-4, 35)))
| Future(Success(apiResult(k-5, 38)))  // All requests by k-1 dropped
v <-- ~2 seconds

Wrapping the rate-limiter in a class

To generalize the rate-limiter, we can create a wrapper class that parameterizes apiCall and filteringStrategy along with the timeWindow, maxReqs, maxReqsPerKey parameters.

case class Request[A](apiKey: String, apiParam: A)

case class RateLimiter[A, B](apiCall: (String, A) => Future[B],
                             filteringStrategy: Int => Flow[Seq[Request[A]], Seq[Request[A]], NotUsed],
                             timeWindow: FiniteDuration,
                             maxReqs: Int,
                             maxReqsPerKey: Int)(implicit ec: ExecutionContext) {
  def flow(): Flow[Request[A], Future[B], NotUsed] =
    Flow[Request[A]].
      groupedWithin(maxReqs, timeWindow).
      via(filteringStrategy(maxReqsPerKey)).
      throttle(1, timeWindow, 1, ThrottleMode.Shaping).
      mapConcat(_.map(req => apiCall(req.apiKey, req.apiParam)))
}

object RateLimiter {
  // Rate-limiting flow that discards excessive API calls from any sources
  def keepToLimitPerKey[A](maxReqsPerKey: Int): Flow[Seq[Request[A]], Seq[Request[A]], akka.NotUsed] =
    Flow[Seq[Request[A]]].map{ g =>
      g.foldLeft((List.empty[Request[A]], Map.empty[String, Int])){ case ((acc, m), req) =>
        val count = m.getOrElse(req.apiKey, 0) + 1
        if (count <= maxReqsPerKey) (req :: acc, m + (req.apiKey -> count))
        else (acc, m + (req.apiKey -> count))
      }._1.toSeq.reverse
    }

  // Rate-limiting flow that drops all API calls from any offending sources
  def dropAllReqsByKey[A](maxReqsPerKey: Int): Flow[Seq[Request[A]], Seq[Request[A]], akka.NotUsed] =
    Flow[Seq[Request[A]]].map{ g =>
      val offendingKeys = g.groupMapReduce(_.apiKey)(_ => 1)(_ + _).
        collect{ case (key, cnt) if cnt > maxReqsPerKey => key }.toSeq
      g.filterNot(req => offendingKeys.contains(req.apiKey))
    }
}

Note that implementations of any available filtering strategies are now kept within the RateLimiter companion object.

A “biased” random-number function

Let’s also create a simple function for generating “biased” random integers for test-running the rate-limiter class.

def biasedRandNum(l: Int, u: Int, biasedNums: Set[Int], biasedFactor: Int = 1): Int = {
  def rand = java.util.concurrent.ThreadLocalRandom.current 
  Vector.
    iterate(rand.nextInt(l, u+1), biasedFactor)(_ => rand.nextInt(l, u+1)).
    dropWhile(!biasedNums.contains(_)).
    headOption match {
      case Some(n) => n
      case None => rand.nextInt(l, u+1)
    }
}

Method biasedRandNum() simply generates a random integer within a given range that skews towards elements in the provided biasedNums list. The biasedFactor (e.g. 0, 1, 2, …) influences the skew-level by forcing the random number generator to repeat “biased” trials, with 0 representing no-bias. A larger biasedFactor value will increase the skew.

For example, biasedRandNum(0, 9, Set(1, 3, 5)) will generate a random integer between 0 and 9 (inclusive), skewing towards generating 1, 3 or 5 with the default biasedFactor = 1.

Test-running the rate-limiter class with random data

def apiCall[A](key: String, param: A)(implicit ec: ExecutionContext): Future[String] =
  Future{s"apiResult($key, $param)"}

val requests: Iterator[Request[Int]] = Vector.tabulate(1200)(_ => biasedRandNum(0, 9, Set(1, 3, 5), 2)).
  zipWithIndex.
  map{ case (x, i) => Request(s"k-$x", i + 1) }.
  iterator

Source.fromIterator(() => requests).
  via(RateLimiter(apiCall, RateLimiter.dropAllReqsByKey[Int], 2.seconds, 500, 20).flow()).
  runForeach(println)

In the above example, you’ll see in the output a batch of up to 500 elements get printed for every couple of seconds. The “biasedFactor” is set to 2 significantly skewing the random apiKey values towards the biasedNums elements 1, 3 and 5, and since filtering strategy dropAllReqsByKey is chosen, a likely observation is that all requests with apiKey k-1, k-3 or k-5 will be dropped by the rate-limiter.

I’ll leave it to the readers to experiment with the rate-limiter by changing the values of parameters in biasedRandNum() as well as constructor fields in class RateLimiter.