<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alex Turner on Medium]]></title>
        <description><![CDATA[Stories by Alex Turner on Medium]]></description>
        <link>https://medium.com/@alexrmturner?source=rss-b71a719cbf17------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*dJBfbh1dJKw_pkC1</url>
            <title>Stories by Alex Turner on Medium</title>
            <link>https://medium.com/@alexrmturner?source=rss-b71a719cbf17------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 09:31:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexrmturner/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Return types in TypeScript — How they can ruin your day]]></title>
            <link>https://medium.com/@alexrmturner/return-types-in-typescript-how-they-can-ruin-your-day-47dc1401f40e?source=rss-b71a719cbf17------2</link>
            <guid isPermaLink="false">https://medium.com/p/47dc1401f40e</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Alex Turner]]></dc:creator>
            <pubDate>Fri, 20 Feb 2026 18:24:48 GMT</pubDate>
            <atom:updated>2026-02-21T17:06:11.321Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5MMHBSwpXrjDuWyv19_SA.png" /></figure><p>Typescript as a language is touted as providing a level of safety through typing that makes it feel more similar to other more strongly typed languages like Java. If you’re like me, and came up in your software journey through enterprises that all used one of the big popular languages, Java or .NET or similar then you’ve built up an idea of what “Type Safety” might mean.</p><p>Over the years, JavaScript has been used to great effect to build web scripting to enhance web pages, and provide a more lively feeling UI for users, or providing more sophisticated ways of interacting with the a page.</p><p>This evolved eventually into full stack single page apps, or SPAs. These application frameworks and libraries like Angular and React give front-end developers similar levels of sophistication in their world as the backend folks have had with things like Spring and Guice, JPA etc. for many years. TypeScript has become the language of choice for implementing these applications as it offers more robustness that plain old JavaScript due to it’s typing.</p><p>Over the last few years, we’ve stepped into a new era, the Node era. Where TypeScript for SPAs became the norm, there are now more and more applications being developed on the backend using TypeScript. This can be really advantageous, allowing front-end applications to leverage the same model structures as the back-end, and in the case of frameworks like NextJS or TRPC quite literally they become one single codebase. Less separation, more type safety, less developer effort to get things complete!</p><p>And so with that pre-amble, I come now to the meat of this article. One critical place where TypeScript’s type safety falls short, and that’s with return types that may yield a non-result. Enter the age-old worst villain of software engineering “NULL”.</p><p>“NULL” has been widely implemented, from SQL to Java to now TypeScript. TypeScript in fact goes so far as to have a number of specific and special variants of null, “undefined”, “NaN”, “Infinity” and so forth that give better ways of distinguishing what sort of “Invalid Value” is present. This is a by and large good thing.</p><p>This is also however where things start to go really wrong. The Typescript compiler doesn’t seem to care if the return type of a function is expressed as a union of a valid type and a nullish type. It treats the resulting value as only the base type:</p><pre>function foo(): Thing | undefined {<br>  return undefined<br>}<br>const x: Thing = foo()</pre><p>This shockingly compiles with no errors! 😱</p><p>As if this isn’t bad enough, the following also produces no errors:</p><pre>function foo(): Thing | undefined {<br>  return undefined<br>}<br>const x = foo().alpha</pre><p>Assuming Thing has a field named alpha, this compiles just fine, and of course at runtime will crash.</p><p>I have seen more bugs due to this single compiler oddness in the last couple of years now using TypeScript on the backend that almost any other kind of error. I don’t understand why TypeScript decided to do it this way, but this is probably one of the biggest source of trivial but serious bugs I’ve ever seen.</p><p>Fortunately, there is a way to do better — by using explicit return object types for both success <em>and</em> failure. By using a union type for result, we can explicit distinuish with type safety between success and failure:</p><pre>interface ThingSuccessResult {<br>  status: &quot;success&quot;<br>  alpha: string<br>}<br><br>interface ThingFailureResult {<br>  status: &quot;failure&quot;<br>  error: any<br>}<br><br>type ThingResult = ThingSuccessResult | ThingFailureResult</pre><p>Now when a method that returns ThingResult is invoked, the compiler will force the code to explicitly disambiguate between success and failure before we can proceed to process the return value.</p><p>The following examples below of nullish async and sync returns all compile just fine except for the case where we have the explicit return result type.</p><pre>interface Thing {<br>  alpha: string<br>  beta: number<br>}<br><br>async function foo() {<br>  const t = await bar()<br>  const v = t.alpha<br>  const u = bar().then(x =&gt; {<br>    const y = x.alpha<br>  })<br>}<br><br>async function fooNull() {<br>  const t = await barNull()<br>  const v = t.alpha<br>  const u = barNull().then(x =&gt; {<br>    const y = x.alpha<br>  })<br>}<br><br>function fooNull2() {<br>  const u = barNull().then(x =&gt; {<br>    const y = x.alpha<br>  })<br>}<br><br>function fooResult() {<br>  const u = barResult().then(x =&gt; {<br>    const y = x.alpha<br>  })<br>}<br> <br>function fooSync() {<br>  const u = barSync()<br>  const y = u.alpha<br>}<br><br>function bar(): Promise&lt;Thing | undefined&gt; {<br>  return undefined<br>}<br><br>function barNull(): Promise&lt;Thing | null&gt; {<br>  return null<br>}<br><br>async function barResult(): Promise&lt;ThingResult&gt; {<br>  return {<br>    status: &quot;failure&quot;,<br>  }<br>}<br><br>function barSync(): Thing | undefined {<br>  return undefined<br>}<br><br>interface SuccessThing {<br>  status: &quot;success&quot;<br>  alpha: string<br>  beta: number<br>}<br><br>interface FailureThing {<br>  status: &quot;failure&quot;<br>  error: any<br>}<br><br>type ThingResult = SuccessThing | FailureThing</pre><p>Using this kind of structure is a solid way to avoid type problems with return values of service methods, and avoid runtime type problems. Its a way to use TypeScripts helpful union type as a structure to prevent bugs.</p><p>I also have to wonder how many LLMs will implement your service methods like this? From what I’ve seen so far, none, at least not without significant extra prompting.</p><p>Of course, you could also implement decent test coverage too, but that’s a topic for another day…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47dc1401f40e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS, Node.js, latency lies, damn lies, and statistics.]]></title>
            <link>https://medium.com/@alexrmturner/nestjs-node-js-latency-lies-damn-lies-and-statistics-fa2e93573d27?source=rss-b71a719cbf17------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa2e93573d27</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Alex Turner]]></dc:creator>
            <pubDate>Fri, 05 Sep 2025 18:56:12 GMT</pubDate>
            <atom:updated>2025-09-05T18:56:12.853Z</atom:updated>
            <content:encoded><![CDATA[<p>… or why I decided to write my own article about Node latency claims.</p><p>I’ve been deep in Node work lately, and Medium sends me a helpful daily email digest of articles mostly focused on Node and Typescript. Each day, I open it up curious to see what there is to learn and apply. Pulling up these articles, there is often a lack of usable, good quality information, and sometimes just wrong information, all of which leaves me disappointed and frustrated.</p><p>I have a confession: this post started life as a reply to one of these articles. It grew longer and longer as more and more data was added, so turning it into an article seemed a better way to contribute than just posting a reply.</p><h3>The Problem with many NodeJS Performance Articles</h3><p>A common theme on Medium lately has been Node “latency” (or more precisely request time) of APIs servers. Many articles are presented talking about optimization techniques, “<em>Get 40% better performance from NodeJS!</em>”</p><p>Problem is, they rarely show good evidence or full reasoning. So I’m not going to write about optimizing Node so much, but focus instead on critical thinking and how to look at your server and gauge it’s performance.</p><p>To provide a bit of background, I came up through the ranks in largely Java based enterprises with some detours through the worlds of PHP, Python, and Scala. When Node first showed up, it seemed like a terrible idea that would be dead in a few years. Boy was I wrong! It provides a simple and effective way to author light-weight API servers that can handle large-volumes of requests with surprising speed and resource efficiency.</p><p>In most cases, it’s my experience that Node doesn’t particularly need much optimization. Node is a brilliant piece of technology that does what it does <em>really</em> well. I’m going to focus on how to look at the numbers and see what’s really going on, presenting and digging into the data points those articles often omit.</p><h3>Setup</h3><p>The service being benchmarked is a Node API server built with express, NestJS, TypeORM, and lots of other bolt-on bits and pieces. NestJS provides many kinds of middleware and interceptors helping you route, parse, validate, and direct your requests. On top of that, this implementation has a good sized layer of additional functionality built on top of that including:</p><ul><li>Request logging with request start time and end time.</li><li>Method instrumentation offset time from request, completion time, payload-per-method cardinality (how many elements are being processed at this point-cut).</li><li>Runtime and call-stack metadata such as memory usage stats, the call chains including stack traces and how many times each entry point and each entry stack is invoked.</li><li>Entry payload object(s), and return object value — truncated if necessary.</li></ul><p>This is a <em>log</em> of logging. The entire lifecycle of each request is captured.</p><p>This information is used to produce detailed visualizations of requests, to reveal hotspots such as slow methods, or places where cardinality is spiking unexpectedly due to things like n+1 query problems.</p><p>At first glance, all this logging must surely add huge latency; <em>Surely we must need to optimize?!</em></p><p>In practice it doesn’t. Even with express, the performance is sufficient. Granted, every use case is different, and for your case, you might want a super high throughput API server, but for most situations, the defaults get the job done.</p><h3>Baseline: Simple Endpoint</h3><p><em>Below is included more or less the full output from Apache Bench below. Complete information paints a complete picture.</em></p><p>Here’s an Apache Bench run against a simple status endpoint:</p><pre>Server Software:        <br>Server Hostname:        localhost<br>Server Port:            3000<br><br>Document Path:          /status/v1/status<br>Document Length:        433 bytes<br><br>Concurrency Level:      10<br>Time taken for tests:   0.286 seconds<br>Complete requests:      100<br>Failed requests:        0<br>Total transferred:      85700 bytes<br>HTML transferred:       43300 bytes<br>Requests per second:    349.06 [#/sec] (mean)<br>Time per request:       28.648 [ms] (mean)<br>Time per request:       2.865 [ms] (mean, across all concurrent requests)<br>Transfer rate:          292.13 [Kbytes/sec] received<br><br>...<br><br>Percentage of the requests served within a certain time (ms)<br>  50%     21<br>  66%     23<br>  75%     27<br>  80%     32<br>  90%     42<br>  95%     55<br>  98%     56<br>  99%     57<br> 100%     57 (longest request)</pre><p>The payload size is just 433 bytes, concurrency is 10, and Apache Bench runs 1000 requests. The API server, expansive telemetry included, pulls off an aggregate of 350 RPS (requests per second) with a mean execution time of 2.9ms per request. The status endpoint represents almost pure overhead, returning a single JSON objecct with server configuration parameters like environment, database connection host, connection pool settings and so forth. It’s used for the load balancer, and to help an engineer verify the correct configuration parameters made it into the runtime. We can see from this simple example that logging and telemetry overhead, method invocation, and inherent “latency” inside Node, Express, and NestJS is <em>negligible</em>.</p><p>When metrics are presented, context is vital. It’s important to ask questions like:</p><ul><li>What endpoint was benchmarked?</li><li>What other services is that endpoint interacting with: database, auth, other things?</li><li>What was the concurrency level?</li><li>What was the payload size?</li><li>What was the elapsed time for the request vs the average time per request over all requests?</li><li>What was the CPU load during this load test?</li><li>What was the Load Average (LA) during this load test?</li></ul><h3>Real Work: Event Endpoint</h3><p>Let’s have a look at a benchmark for an endpoint that fetches an Event object. This test is run at a concurrency of 100 to simulate a crushing server load to see how that impacts request times:</p><pre>Server Hostname:        localhost<br>Server Port:            3000<br><br>Document Path:          /product/event/v1/event/250090<br>Document Length:        6713 bytes<br><br>Concurrency Level:      100<br>Time taken for tests:   47.471 seconds<br>Complete requests:      1000<br>Failed requests:        0<br>Total transferred:      7139000 bytes<br>HTML transferred:       6713000 bytes<br>Requests per second:    21.07 [#/sec] (mean)<br>Time per request:       4747.086 [ms] (mean)<br>Time per request:       47.471 [ms] (mean, across all concurrent requests)<br>Transfer rate:          146.86 [Kbytes/sec] received<br><br>...<br><br>Percentage of the requests served within a certain time (ms)<br>  50%   4746<br>  66%   4815<br>  75%   4840<br>  80%   4876<br>  90%   4911<br>  95%   4949<br>  98%   5000<br>  99%   5004<br> 100%   5010 (longest request)</pre><p>Even with the logging and telemetry, this endpoint sustains ~21 RPS for a 6kB payload. Maybe my personal laptop is just really fast compared with a typical modest cloud server? Next let’s try this endpoint on a real server instance hosted in our cloud provider.</p><h3>Cloud Instance Benchmarks</h3><p>The development server is storing data in a cloud based datastore, and running on a modest linux instance: 16GB RAM and 2vCPUs.</p><pre>Server Software:        <br>Server Hostname:        ##Redacted##<br>Server Port:            443<br>SSL/TLS Protocol:       TLSv1.2,ECDHE-RSA-AES256-GCM-SHA384,2048,256<br>Server Temp Key:        ECDH X25519 253 bits<br>TLS Server Name:        ##Redacted##<br>Document Path:          /product/event/v1/event/#redacted#<br>Document Length:        14589 bytes<br><br>Concurrency Level:      30<br>Time taken for tests:   5.176 seconds<br>Complete requests:      200<br>Failed requests:        0<br>Total transferred:      3043400 bytes<br>HTML transferred:       2917800 bytes<br>Requests per second:    38.64 [#/sec] (mean)<br>Time per request:       776.475 [ms] (mean)<br>Time per request:       25.882 [ms] (mean, across all concurrent requests)<br>Transfer rate:          574.15 [Kbytes/sec] received<br><br>Connection Times (ms)<br>              min  mean[+/-sd] median   max<br>Connect:      248  268  16.7    263     339<br>Processing:   305  380  74.8    383     662<br>Waiting:      304  343  58.4    320     580<br>Total:        554  649  87.9    646    1001<br><br>Percentage of the requests served within a certain time (ms)<br>  50%    646<br>  66%    660<br>  75%    667<br>  80%    682<br>  90%    744<br>  95%    879<br>  98%    965<br>  99%    987<br> 100%   1001 (longest request)</pre><p>Solid result! Averaging at 38 RPS serving a fairly good sized API endpoint which returns around 15kB of data, the response time averages ~650ms.</p><p>Looking at the ~650ms response time average, let’s break that down, and see where the time is really going. Starting with the connection times table, about 250ms is connection overhead, TCP/TLS handshake and WAF transit (Web Application Firewall), and then an additional 300ms is spent waiting for external I/O to complete. The Node portion of the request has an aggregated average time of 26ms per request.</p><p>Let’s do the same test, but this time at a concurrency of 2 and see what changes:</p><pre>Server Software:        <br>Server Hostname:        #redacted#<br>Server Port:            443<br>SSL/TLS Protocol:       TLSv1.2,ECDHE-RSA-AES256-GCM-SHA384,2048,256<br>Server Temp Key:        ECDH X25519 253 bits<br>TLS Server Name:        #redacted#<br><br>Document Path:          /product/event/v1/event/#redacted#<br>Document Length:        14589 bytes<br><br>Concurrency Level:      2<br>Time taken for tests:   61.785 seconds<br>Complete requests:      200<br>Failed requests:        0<br>Total transferred:      3043400 bytes<br>HTML transferred:       2917800 bytes<br>Requests per second:    3.24 [#/sec] (mean)<br>Time per request:       617.854 [ms] (mean)<br>Time per request:       308.927 [ms] (mean, across all concurrent requests)<br>Transfer rate:          48.10 [Kbytes/sec] received<br><br>Connection Times (ms)<br>              min  mean[+/-sd] median   max<br>Connect:      238  262  15.5    260     371<br>Processing:   305  350  39.7    324     446<br>Waiting:      305  316   7.3    315     368<br>Total:        562  613  43.6    590     776<br><br>Percentage of the requests served within a certain time (ms)<br>  50%    590<br>  66%    649<br>  75%    653<br>  80%    654<br>  90%    663<br>  95%    672<br>  98%    706<br>  99%    737<br> 100%    776 (longest request)</pre><p>Taking the above test in isolation, the result looks pretty bad. 600ms mean request time and just 3.24 RPS. Surely it’s time to start looking for optimizations! Not so fast. Let’s take a moment to dig into the details of what’s happening.</p><p>At concurrency 2 and concurrency 30, the per-request completion time was not that different; around 600ms and 650ms. This represents a difference of about a 10% at P50, and about 30% at P99. Aggregated average is just 25ms per request. From this it’s apparent that 90–95% of the request time is spent <em>outside</em> of Node. Applying the theory of constraints: <em>find the place that’s most constrained, and apply improvement there first</em>, or put another way, <em>applying optimizations anywhere but the most constrained place is effort wasted</em>. Most of the time in this request is split between connection and transit overhead through the WAF, and round-trip time to external I/O. To Improve “latency” these would be the first places to work on. Optimizing the Node portion would represent effort put towards an area that’s not going to make a significant difference. Node’s event loop is working perfectly, allowing high concurrency, keeping server-time low, and taking just 25ms per request. It’s simply not the most constrained portion of this system.</p><p>One of the biggest reasons for “Why Node” is its asynchronous nature. This is Node’s biggest advantage, the moment you touch anything external, it pushes you into an async/await paradigm. It’s almost impossible to do anything significant in Node without ending up with every darn function returning a Promise, and once a dependent function returns a Promise, your function returns must then return a Promise, if it it’s hidden behind async/await syntax. There’s no way I know of to force Node to act synchronously, and that’s kind of the point of Node. Promises can be chained poorly, doing lots of asynchronous things end-to-end rather than in parallel and cause slow total response times. But even though these requests might be slower, they’re still fully non-blocking! Node stubbornly refuses to tie up server resources.</p><h3>Conclusion</h3><p>Treat articles promising Node optimizations with skepticism. Look at what context they’re providing, and if it’s applicable for your use case. Does the article detail which changes yielded what specific, measurable improvements and explain why?</p><p>Start first with:</p><ul><li>Benchmarking <em>real</em> endpoints.</li><li>Understand which numbers are the important ones for you and your situation — what are the needs of the customer? Total concurrent throughput is distinct from average time for a request to complete (TTLB).</li><li>Check the throughput of many endpoints, with different payload sizes, and concurrency settings to get a complete picture.</li><li>Identify the slowest parts of the system that contribute to the overall request time, before you jump in to optimization.</li></ul><p>Ensure you’ve got the basics of performant systems implemented first:</p><ul><li>Optimize the datastore with appropriate indexes.</li><li>Make sure HTTP Keep-Alive is working properly.</li><li>Leverage HTTP max-age and cache-control headers for your endpoints — the fastest request is the one that never needs to be made.</li><li>Add a simple in-process server memory cache. If that’s not enough, you can always deploy a KV store like Redis to get a bigger and centralized cache.</li></ul><p>Optimization can be fun, but first ask if you truly need it in your situation? More than anything else, do your own measurements, and as the saying goes: “there are lies, damn lies, and statistics!”. Be skeptical, measure carefully, and optimize where it matters.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa2e93573d27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On Serialization in Applications]]></title>
            <link>https://medium.com/@alexrmturner/on-serialization-in-applications-686e2f4af3f?source=rss-b71a719cbf17------2</link>
            <guid isPermaLink="false">https://medium.com/p/686e2f4af3f</guid>
            <category><![CDATA[application-development]]></category>
            <category><![CDATA[data-serialization]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Alex Turner]]></dc:creator>
            <pubDate>Mon, 03 Jan 2022 05:53:27 GMT</pubDate>
            <atom:updated>2022-01-03T05:53:27.850Z</atom:updated>
            <content:encoded><![CDATA[<p>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.</p><p>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.</p><p>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.</p><p>We can think of most application as a chain of transforms:</p><pre>UserInput =&gt; UserModel =&gt; ApplicationModel</pre><pre>(ApplicationModel =&gt; UserModel =&gt; UserResponse) + <br>  (ApplicationModel =&gt; DataStoreModel =&gt; DataStoreResponse)</pre><p>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.</p><p>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.</p><p>How do we satisfy that complexity? In what part of the application should serialization live?</p><p>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.</p><p>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</p><pre>implicit val clientWriter = Json.writes[Client]</pre><p>or, I can craft each field specifically</p><pre>implicit val clientWriter = new Writes[Client] {<br>  override def write(x: Client) = {<br>    Json.obj(<br>      &quot;id&quot; -&gt; x.id<br>      &quot;name&quot; -&gt; x.name<br>      &quot;createdTimestamp&quot; -&gt; x.createdTimestamp<br>    )<br>  }<br>}</pre><p>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:</p><pre>val <em>isoDateFormatter </em>= DateTimeFormatter<br>  .<em>ofPattern</em>(&quot;yyyy-MM-dd&#39;T&#39;HH:mm:ss.SSS&#39;Z&#39;&quot;)</pre><pre>def isoDateFormat(date: java.util.Date) = {<br>  <em>isoDateFormatter<br>    </em>.format(<br>      Instant.<em>ofEpochMilli</em>(date.getTime).atOffset(ZoneOffset.<em>UTC</em>)<br>    )<br>}</pre><pre>implicit val <em>timestampWrites</em>: Writes[java.sql.Timestamp] = (timestamp: java.sql.Timestamp) =&gt; if (timestamp != null) {<br>  <em>JsString</em>(<em>isoDateFormat</em>(timestamp))<br>} else JsNull</pre><p>And then there’s a corresponding reader:</p><pre>implicit val clientReads = (<br>  (JsPath \ &quot;id&quot;).as[Long] and<br>  (JsPath \ &quot;name&quot;).as[String] and<br>  (JsPath \ &quot;createdTimestamp&quot;).as[java.sql.Timestamp]<br>)(Client.apply _)</pre><p>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!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=686e2f4af3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>