In Rails 7.1, support for MessagePack has been added, and it can be used with
config.active_support.message_serializer will also accept
:message_pack_allow_marshal as serializers.
What is MessagePack?
MessagePack is an efficient binary serialization format that enables the exchange of data among multiple languages, similar to JSON.
It is faster and more compact compared to JSON, as it is optimized for binary data serialization. Specifically designed for efficiently representing complex data structures, it makes the payload smaller and faster to serialize and deserialize.
The following is a message serialized by
Unlike BSON, which is a similar serialization format and less verbose, BSON is designed for faster in-memory manipulation, whereas MessagePack is designed for efficient network communication.
Before Rails 7.1, Rails didn’t have native support for serializing using MessagePack. We had to install the msgpack gem and serialize the message.
To use MessagePack with
ActiveSupport::MessageEncryptor, we need to pass serializer argument with the value
MessagePack. This ensures that the messages are serialized and deserialized appropriately during both encryption and decryption processes.
MessagePack is supported starting from Rails 7.1, with msgpack integrated into it. Rails has also introduced a new class called
ActiveSupport::MessagePack, designed to serialize most basic Ruby data types.
To configure MessagePack as the default serializer in the Rails application, include the following in
In Rails 7.1, the default serializer is
json_allow_marshal. However, it can fall back to deserializing with
Marshal so that legacy messages can still be read. We can set MessagePack as the default serializer in the app by using the
config.active_support.message_serializer configuration method and setting the value as
Since MessagePack is configured as the message serializer using the
config.active_support.message_serializer method, we do not need to pass the serializer argument to
ActiveSupport::MessageEncryptor as we did in the previous Rails version.
MessageEncryptor will serialize the message using
MessagePack during both encryption and decryption processes. To check the default serializer, we can run
ActiveSupport::Messages::Codec.default_serializer, which returns