Sitemap
Alex Turner

Alex Turner

On Serialization in Applications

4 min readJan 3, 2022

For many years, I’ve worked on applications. Before there was a ‘front-end’ and a ‘back-end’. I started in the days when ColdFusion was a thing. When we were still all writing our data to big expensive Oracle databases, and MySQL and PostgreSQL were just getting started. Long long before the likes of DynamoDB showed up.

Ever since way back then, one of the most basic building blocks of application development hasn’t changed much at all. The issue of serialization. How does data get communicated between one application and another in a way that the two applications can mutually interpret.

Breaking down a modern application into it’s component parts, it can be viewed as a translation platform that takes input from the user in some form, deserializes it from it’s arrival form, turns it into data, often in the form of objects that the business logic can work with, and then more than likely, sends some kind of response back to the user on one hand, and another down to some persistence system on the other to keep track of what was done, even if it’s only in the form of logging, but more commonly as some kind of record of either what happened, and the resulting state.

We can think of most application as a chain of transforms:

UserInput => UserModel => ApplicationModel(ApplicationModel => UserModel => UserResponse) + 
(ApplicationModel => DataStoreModel => DataStoreResponse)

Many applications, even today decide that the Models themselves were the right place to drive serialization from. We can annotate things like POJOs and have a serialization library like Jackson do the magic that turns a POJO into a JSON representation, or an XML document. In the case of Javascript, often these two things are the same — a JSON document.

There are a couple of big reasons why this is a bad approach. Firstly, if the application design is following Domain Driven Design, which hopefully it is, the aggregate root simultaneously contains more information and less information than is needed to fulfill most API responses. To get what is needed, the application composes objects, or, decomposes objects to provide just the right amount of data for any given API response. A simple one-to-one mapping between the model that’s persisted, or used for business logic, and the response doesn’t satisfy what’s desired. Secondly, serialization may depend on context. Certain API clients have differing visibility than others for a given endpoint depending on authorization, not necessarily even just more or less, but potentially different shapes through the same domain. Whilst the application can start out assuming a simple mapping, as it grows to satisfy more complex use cases, more complexity starts to be demanded.

How do we satisfy that complexity? In what part of the application should serialization live?

If serialization is driven at the edge of the application, and is dependent on context, one approach is to locate it at the boundaries between the application and the outside. The concern of serialization is then managed by the controller on the way out, and the way in to the clients and users. And by the repository service, or DTOs on the way out and the way in from the datastore.

Get Alex Turner’s stories in your inbox

Join Medium for free to get updates from this writer.

It’s still possible to manage this serialization with annotated POJOs, with one set of classes for client-facing models, one for internal representation, and one for datastore model. That’s a lot of POJOs, and with that approach it’s still hard to deal with multiple authorization levels neatly. For me, I like to use a library like the play JSON library that allows me to craft serializers at the level of customization I need. If I want straight one-to-one, the library takes care of reflection, and I can just write

implicit val clientWriter = Json.writes[Client]

or, I can craft each field specifically

implicit val clientWriter = new Writes[Client] {
override def write(x: Client) = {
Json.obj(
"id" -> x.id
"name" -> x.name
"createdTimestamp" -> x.createdTimestamp
)
}
}

With the play json library, serializers compose, so if I want to have a specific timestamp format, I can define a writer for java.sql.Timestamp if I’m using that class, and format it just how I want. As long as it’s in scope for the clientWriter, it’ll be used:

val isoDateFormatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
def isoDateFormat(date: java.util.Date) = {
isoDateFormatter
.format(
Instant.ofEpochMilli(date.getTime).atOffset(ZoneOffset.UTC)
)
}
implicit val timestampWrites: Writes[java.sql.Timestamp] = (timestamp: java.sql.Timestamp) => if (timestamp != null) {
JsString(isoDateFormat(timestamp))
} else JsNull

And then there’s a corresponding reader:

implicit val clientReads = (
(JsPath \ "id").as[Long] and
(JsPath \ "name").as[String] and
(JsPath \ "createdTimestamp").as[java.sql.Timestamp]
)(Client.apply _)

The one big warning with this approach is that it’s vital to make sure there are tests that ensure that in the same context, the serialization is symmetric. Make sure what’s being written, is able to be read back again!

--

--