Shardcake is now Shard: introducing Shard 3.0

11 min read
Shardcake is now Shard: introducing Shard 3.0

In 2022, I created Shardcake, a Scala library to distribute entities across multiple servers (sharding) and interact with them using their ID, without knowing their actual location (location transparency). Today, I’m releasing its successor: Shard 3.0! Besides the new name, this release brings major changes to the API and to the internals.

If you have never used Shardcake, my post on supporting high-performance response streaming in Shardcake gives a good idea of what it looks like.

From Shardcake to Shard

I created Shardcake at Devsisters, where it has been running in production for Cookie Run: Kingdom since March 2022. It came after years of using Akka Cluster Sharding: the code has nothing in common with Akka, but credit goes to them for some of the ideas and concepts. It is also used in production at Soundtrack, where I work now.

Since I left Devsisters, I’ve continued the project under my own name, as Shard. A new name was also the perfect opportunity for a fresh start: I could finally make the breaking changes I had in mind for a long time. Shard now lives next to my other libraries in the ghostdogpr stack, and as you’ll see below, it builds on some of them.

For this release, I also took some inspiration from Effect Cluster. It started as a port of Shardcake to TypeScript, before changing the design and adding its own improvements. I liked several of those improvements, so I brought some of them back to Scala.

The new name changes the coordinates: artifacts are now "com.github.ghostdogpr" %% "shard-xxx" and the package is shard instead of com.devsisters.shardcake. I also took the opportunity to drop Scala 2, so that Shard can fully benefit from the improvements of Scala 3 (the new API relies on features like union types). Shard requires Scala 3.9 LTS or later. The version number continues from Shardcake, which is why the first release of Shard is 3.0.

A simpler API

Let’s start with the most visible change: the API to define messages, to process them in entities, and to send them.

Messages

In Shardcake, a message that expected a reply carried a Replier:

sealed trait GuildMessage

object GuildMessage {
  case class Join(userId: String, replier: Replier[Try[Set[String]]]) extends GuildMessage
  case class Leave(userId: String)                                    extends GuildMessage
}

This always felt a bit awkward: the replier is not really part of the message, it’s a callback that the entity has to remember to call. And since there was no way to declare errors, they had to be encoded in the type of the reply. At Devsisters, all our messages ended up replying with a Try.

In Shard, the Replier is gone. Instead, each message declares the type of the errors it can fail with and the type of its reply, as two type parameters:

case class GuildFull(maxMembers: Int)

enum GuildMessage[E, A] {
  case Join(userId: String)  extends GuildMessage[GuildFull, Set[String]]
  case Leave(userId: String) extends GuildMessage[Nothing, Unit]
}

Handlers

In Shardcake, the behavior of an entity was a loop consuming a queue of messages and replying through the Replier of each one:

def behavior(entityId: String, messages: Queue[GuildMessage]): RIO[Sharding, Nothing] =
  Ref.make(Set.empty[String]).flatMap { state =>
    messages.take.flatMap {
      case Join(userId, replier) =>
        state.get.flatMap(members =>
          if (members.size >= 5) replier.reply(Failure(new Exception("Guild is full")))
          else state.updateAndGet(_ + userId).flatMap(members => replier.reply(Success(members)))
        )
      case Leave(userId)         =>
        state.update(_ - userId)
    }.forever
  }

The problem is that nothing forces you to reply. In production, we had cases where an error was not handled properly and replier.reply was never called: instead of receiving an error, the caller waited until the timeout. Not great!

In Shard, the behavior is called when the entity starts and returns a handler, whose handle method simply returns the result of each message:

def behavior(entityId: String): ZIO[Scope, Nothing, Guild.Handler] =
  Ref.make(Set.empty[String]).map { state =>
    new Guild.Handler {
      def handle[E, A](message: GuildMessage[E, A]): IO[E, A] =
        message match {
          case Join(userId)  =>
            state.get.flatMap(members =>
              if (members.size >= 5) ZIO.fail(GuildFull(5))
              else state.updateAndGet(_ + userId)
            )
          case Leave(userId) =>
            state.update(_ - userId)
        }
    }
  }

When you pattern match on a message, the compiler knows which E and A it declared: in the Join branch, it checks that you return a Set[String] and only fail with GuildFull. And there is no way to forget a reply anymore: the sender always gets the result of handle, or an EntityDefect if the entity died.

The behavior also gets a Scope, which is closed when the entity stops. Saving the state of an entity is now just a ZIO.addFinalizer, where Shardcake required a special termination message.

Sending messages

On the sender side, the message no longer takes a callback, and the error type tells you exactly what can go wrong:

// Shardcake
val joined: Task[Try[Set[String]]] = guild.send("guild1")(Join("user1", _))

// Shard
val joined: IO[GuildFull | ClusterError, Set[String]] = guild.send("guild1")(Join("user1"))

ClusterError covers the failures of the cluster itself, such as SendTimeout, MailboxFull or EntityDefect, so you can handle them separately from the errors of your domain.

Streaming replies are declared in the message type too, with Streamed[E2, A] (or Duplex[In, E2, A] to also receive a stream of inputs). stream returns a ZStream directly instead of a Task of a stream, and the compiler rejects a streaming message passed to send.

More control over entities

A few new options give you more control over how entities process their messages. An entity still processes its messages one at a time by default, but the concurrency option lets it process several at once, and messages marked as Concurrent (typically, reads) can run alongside the others. Each entity also has a bounded mailbox (4,096 messages by default): when it’s full, new messages fail with MailboxFull instead of piling up in memory. And when a sender stops waiting for a reply (after a timeout, for example), the processing of the message is interrupted, unless the message is marked as Uninterruptible.

Entity interceptors let you wrap the life of entities and the processing of each message, which is useful for logging, metrics or tracing. Finally, Sharding exposes a few more methods to inspect the cluster (the entities running on a pod, which pod holds a given entity, the registered pods), which comes in handy for admin and debug pages.

I also went through the whole codebase and fixed a number of reliability issues along the way, such as a singleton that could briefly run on two pods at the same time during a rolling update.

Any encoding for your messages

In Shardcake, serialization was a single Serialization layer shared by all the messages of a pod:

trait Serialization {
  def encode(message: Any): Task[Array[Byte]]
  def decode[A](bytes: Array[Byte]): Task[A]
}

Since it knows nothing about the types it encodes, only a reflective serializer that writes the type into the bytes can implement it. In practice, that meant Kryo. Kryo is convenient, since any type works without deriving anything, but it is also strict: most changes to a message break the wire format. I have been bitten by this several times, and I know other Shardcake users have been too: during a rolling update, old pods can’t read the messages of new pods, or vice versa. Relying on reflection also caused some weird issues, like when the way Scala 3 encodes lazy vals broke our serialization (I wrote about it in Debugging session #2).

In Shard, this layer is replaced by a MessageCodec[Msg] type class, which encodes the messages of one entity type, along with their replies and errors:

trait MessageCodec[Msg[_, _]] {
  def encodeMessage[E, A](message: Msg[E, A]): Array[Byte]
  def decodeMessage(bytes: Array[Byte]): Msg[Any, Any]
  def replyCodec[E, A](message: Msg[E, A]): ReplyCodec
}

A given MessageCodec is required where the entity type is declared, and you pick the backend by importing it:

import shard.kryo.given

object Guild extends EntityType[GuildMessage]("guild")

Kryo is still there if you want it, but since the codec now knows the type of the messages, it can also be derived at compile time. Shard comes with a backend for Proteus, my code-first Protobuf library (see Protobuf Goes Scala-First). Replace shard.kryo.given with shard.proteus.given, and your messages are sent in the Protobuf format, derived from your Scala types. This means they follow Protobuf’s evolution rules: for example, adding a field at the end of a message is safe, so rolling updates that change messages become much easier.

There is one constraint: as in Protobuf, the top-level types must be messages, so replies and errors must be case classes, sealed traits or enums. For example, the Set[String] returned by Join would need to be wrapped in a case class like Members(userIds: Set[String]).

Proteus can also render the .proto file of an entity’s messages, replies and errors, which is handy to share the contract with other teams or other languages:

import shard.proteus.given

val proto: String = ProteusMessageCodec.dependency[GuildMessage]("guild", "com.example.guild").render(Nil)
// syntax = "proto3";
//
// package com.example.guild;
//
// message GuildMessage {
//     oneof value {
//         Join join = 1;
//         Leave leave = 2;
//     }
// }
//
// message Join {
//     string user_id = 1;
// }
//
// message Leave {
//     string user_id = 1;
// }
//
// message GuildFull {
//     int32 max_members = 1;
// }
//
// message Members {
//     repeated string user_ids = 1;
// }

Each entity type can use a different backend, and if you need something else (JSON, an existing Protobuf setup, etc.), you only have to implement MessageCodec.

One Shard Manager to rule them all

In Shardcake, a Shard Manager (and its storage) managed a single group of pods. We had several services using Shardcake, which meant deploying and operating one Shard Manager for each of them. Not ideal!

Shard introduces roles: each pod has a role, and a single Shard Manager can manage pods of different roles. Each role is managed independently, as if it had its own Shard Manager, with its own shards, assignments and rebalancing. Pods only send messages to entities hosted by pods of the same role, and a singleton runs once in each role that registers it.

// on the pods of a service
Config.default.copy(role = Role("game"))

// on the Shard Manager, the number of shards can differ per role
ManagerConfig.default.copy(numberOfShards = {
  case Role("game") => 1000
  case _            => 300
})

If you only have a single group of pods, there is nothing to do: they all get the default role and behave as before.

A leaner stack

Shard also has fewer dependencies, and builds on other libraries of the ghostdogpr stack.

It might be surprising coming from the author of Caliban, but the Shard Manager doesn’t use GraphQL anymore! In Shardcake, it exposed a GraphQL API, while pods talked to each other with gRPC. In Shard, everything uses gRPC, built with Proteus. This means Caliban, zio-http and sttp are no longer needed, and Kubernetes probes can use the standard gRPC health service of the Shard Manager.

For storage, the default Redis implementation now uses Sage, my Redis and Valkey client for Scala 3. The redis4cats and Redisson implementations are still available, and all three store data in the same format, so you can switch between them.

Under the hood, Shard is also faster: in my benchmarks, sending messages is about 1.7 times faster than with Shardcake, both to local and remote entities, and some scenarios got much better, like stopping a large number of entities at once.

Migrating from Shardcake

The migration guide lists everything you need to change in your code: the new artifacts and package, messages, behaviors, registration and the renamed Messenger methods (sendAndReceiveStream is now simply stream, for example). Most changes are mechanical, with compiler errors pointing to the places that need updating.

Upgrading a running cluster requires a bit more care. The protocol between pods, the Shard Manager API and the stored data have all changed, so Shardcake and Shard pods can’t be part of the same cluster, and a rolling update from one to the other is not possible. The simplest way is to accept a short downtime: stop the Shardcake cluster, then start the Shard one. If you can’t afford that, run Shard as a separate cluster next to the old one (a blue/green deployment), with its own Shard Manager and storage, then move the traffic to it. The guide explains how to do that safely. Once on Shard, rolling updates between Shard versions work again.

What’s next

This release was mostly about the API and the foundations, and there is a lot more to come! Next on my list are explicit delivery guarantees, to choose for each message between at-most-once and at-least-once delivery (with AtMostOnce and AtLeastOnce markers), and entity storage, to save and restore the state of entities without doing it by hand in each behavior.

All these improvements will be made in a compatible way: from 3.0 on, you will always be able to upgrade Shard with a rolling update.

Getting started

Shard is split into modules, so that you only pick the protocol, serialization and storage you need. Check out the documentation, starting with Getting Started, and the examples.

Shard 3.0 is much closer to what I originally wanted Shardcake to be. There are still plenty of things I want to add, but I’m happy with the foundations now. If you’re a Shardcake user, give Shard a try and let me know how the migration goes. Feedback and contributions are welcome!