<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Maciej Toporowicz</title>
    <description>The latest articles on DEV Community by Maciej Toporowicz (@maciejtoporowicz).</description>
    <link>https://dev.to/maciejtoporowicz</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F346495%2F6a09f1ec-3fe1-49c0-a1c2-45d623c8b3bf.jpg</url>
      <title>DEV Community: Maciej Toporowicz</title>
      <link>https://dev.to/maciejtoporowicz</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/maciejtoporowicz"/>
    <language>en</language>
    <item>
      <title>Transactional Outbox Pattern in a monolithic application</title>
      <dc:creator>Maciej Toporowicz</dc:creator>
      <pubDate>Thu, 16 Apr 2020 09:36:10 +0000</pubDate>
      <link>https://dev.to/maciejtoporowicz/transactional-outbox-pattern-in-a-monolithic-application-1ooc</link>
      <guid>https://dev.to/maciejtoporowicz/transactional-outbox-pattern-in-a-monolithic-application-1ooc</guid>
      <description>&lt;p&gt;Typically I can see the Transactional Outbox Pattern mentioned in the context of microservices and, to be honest, it's a bit surprising to me - to my mind it is as relevant in the context of monolithic applications.&lt;/p&gt;

&lt;p&gt;In this article, I'll describe the pattern in detail and then provide an implementation example with Kotlin, Spring and PostgreSQL.&lt;/p&gt;

&lt;h1&gt;
  
  
  What is it for?
&lt;/h1&gt;

&lt;p&gt;The transactional outbox pattern describes how to achieve reliable communication. The use case is: you'd like to &lt;strong&gt;atomically&lt;/strong&gt; make an update to the database &lt;strong&gt;and&lt;/strong&gt; invoke another action, typically on an external system. This action could be:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;calling an external API, e.g. by making an HTTP request;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Example scenario&lt;/strong&gt;: a user creates an account in our application, so we'd like to save the account in the database and send a welcome e-mail using AWS SES.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;publishing a message to a queue;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Example scenario&lt;/strong&gt;: an order is placed in our shopping app, so we'd like to save it to the database and enqueue an &lt;code&gt;OrderPlaced&lt;/code&gt; event in AWS SQS.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;in Domain Driven Design - updating another aggregate. This is an action invoked on the same system as the original database transaction. It would mean you'd like to &lt;em&gt;atomically&lt;/em&gt; run &lt;em&gt;two separate&lt;/em&gt; database transactions;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Example scenario&lt;/strong&gt;: an order is placed in our shopping app, so we'd like to save the order and an invoice for it - order and invoice being two separate aggregates.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;/li&gt;
&lt;/ul&gt;




&lt;h3&gt;
  
  
  Side note
&lt;/h3&gt;

&lt;p&gt;To my mind, the DDD example translates nicely into "calling an external API" or "publishing a message to a queue" when talking about microservices. Microservices may often represent specific bounded contexts and it is very likely that there would be a need to make an update in multiple contexts atomically. The transactional outbox pattern may prove to be very useful to make the communication between them reliable&lt;/p&gt;




&lt;p&gt;Let's first take a look at the problem that this pattern lets us solve.&lt;/p&gt;

&lt;h1&gt;
  
  
  The problem with transactional consistency
&lt;/h1&gt;

&lt;p&gt;Let's take a look at the "welcome email" example. When a user creates an account in our app, we'd like to reliably save it to the database and sent a welcome email using &lt;code&gt;AWS SES&lt;/code&gt;. We could have the following piece of code in our application:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;databaseTransaction {
    persist(account) // call to the database
}
sendWelcomeEmailFor(account) // call to SES
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now, what if the call to &lt;code&gt;SES&lt;/code&gt; fails? We'll be left with an &lt;code&gt;account&lt;/code&gt; in our database, but the user will never get the welcome email.&lt;/p&gt;

&lt;p&gt;One might say that with &lt;code&gt;SES&lt;/code&gt; having an uptime of at least 99.9% we can be &lt;em&gt;virtually sure&lt;/em&gt; these two instructions will run just fine. But the failure may also be caused by us. We could e.g. configure our &lt;code&gt;SES&lt;/code&gt; client with wrong credentials.&lt;/p&gt;

&lt;p&gt;What if we can't or simply don't want to lose our messages?&lt;/p&gt;

&lt;p&gt;We can't do the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;databaseTransaction {
    persist(account) // call to the database
    sendWelcomeEmailFor(account) // call to SES
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;In case of a network issue we may not be able to reach &lt;code&gt;SES&lt;/code&gt;. We'll rollback the &lt;code&gt;databaseTransaction&lt;/code&gt;, so the account will not be saved. At the same time it means our users won't be able to create an account if &lt;code&gt;SES&lt;/code&gt; is unreachable, which may not be perfect from the business perspective.&lt;/p&gt;

&lt;p&gt;Another possible network issue may cause the response from &lt;code&gt;SES&lt;/code&gt; not come back to us even though the call succeeds behind the scenes. We'll rollback the &lt;code&gt;databaseTransaction&lt;/code&gt;, but the welcome email will be sent even though the related account is not in our database. This kind of inconsistency may not be desired either.&lt;/p&gt;

&lt;p&gt;Another possibility is that sending the email succeeds, but the commit of &lt;code&gt;databaseTransaction&lt;/code&gt; fails for some reason. We'll end up with the same inconsistency as with the "lost response" scenario.&lt;/p&gt;

&lt;h1&gt;
  
  
  Why not just use two-phase-commit?
&lt;/h1&gt;

&lt;p&gt;Apart from the possibility that we may not be able (or not easily able) to use 2PC with the tools we chose, we need to take into account that 2PC is a synchronous protocol. It means we need to wait until all the participants of the transaction completed their actions and are ready to commit. &lt;/p&gt;

&lt;p&gt;In our "welcome email" example, imagine a user needs to wait until the email is sent to receive a successful response. Or worse - as already described - the user is unable to create the account because of &lt;code&gt;SES&lt;/code&gt; being down. Of course it depends on what the business needs, but I suspect that in general it'd be fine from the business perspective to let the user create an account even though the email service is down, and send the email as soon as it is up and running again.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;I recommend the following article on this subject: &lt;a href="https://www.enterpriseintegrationpatterns.com/ramblings/18_starbucks.html"&gt;Starbucks Does Not Use Two-Phase Commit&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To sum up - 2PC makes the communication between services synchronous, effectively reducing the availability of our service because we're depending on the availability of all the participants of the transaction. We won't be able to complete a transaction if a particular participant is down. What's more, our performance may suffer due to a participant taking a long time to finish its work.&lt;/p&gt;

&lt;h1&gt;
  
  
  The pattern
&lt;/h1&gt;

&lt;p&gt;The idea is simple. In our database we create an additional table called e.g. &lt;code&gt;outbox_message&lt;/code&gt;. We can then change our code to the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;databaseTransaction {
    persist(account) // 'insert into account ...'
    persist(accountCreatedEvent) // 'insert into outbox_message ...'
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;We should be now able to respond to the user that the account has been successfully created. We still need to send the welcome email though.&lt;/p&gt;

&lt;p&gt;Now, there are two strategies for processing the messages from the &lt;code&gt;outbox_message&lt;/code&gt; table:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;polling the 'outbox_message' table:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;It means setting up e.g. a CRON job or a timer in your application to read and process the messages.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;transaction log tailing:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;It means monitoring the database's transaction log file to see what gets inserted into the &lt;code&gt;outbox_message&lt;/code&gt; table and reacting to the inserts.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I'll describe only the polling mechanism a.k.a. 'the polling publisher'. Two reasons for it:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;to my mind it is much simpler to implement;&lt;/li&gt;
&lt;li&gt;I have not had a chance to implement the second one yet.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you feel like reading up on it, you can refer to &lt;a href="https://microservices.io/patterns/data/transaction-log-tailing.html"&gt;Transaction Log Tailing @ microservices.io&lt;/a&gt; - I believe it is a good start.&lt;/p&gt;

&lt;h1&gt;
  
  
  Polling publisher
&lt;/h1&gt;

&lt;p&gt;In our application, somewhere in the background, we need to read the message from the &lt;code&gt;outbox_message&lt;/code&gt; table, send the welcome email and then mark the message as &lt;code&gt;processed&lt;/code&gt; so that it does not get processed again. We'll basically implement a simple queue in the database. &lt;/p&gt;

&lt;p&gt;We may set up a CRON job or a timer in our application to do the polling.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;each n milliseconds {
    databaseTransaction {
        message = readLastOutboxMessage()
        process(message) // send email using AWS SES
        markAsProcessed(message)
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;At first it may look as if we were back to the original problem because we're trying to make a call to an external service in the middle of a database transaction. It is, however, not true. If we analyze what happens when any of the steps fail, we'll see that the message will be delivered &lt;em&gt;eventually&lt;/em&gt;. There are, however, two specific scenarios:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;sending the email succeeds behind the scenes but we don't receive the response (e.g. due to network issue);&lt;/li&gt;
&lt;li&gt;commit of the transaction fails;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In both scenarios, the email will be sent, but we won't mark the message as processed. It means the message will be processed one more time and, as a result, the email will be sent more than once. &lt;strong&gt;The transactional outbox pattern guarantees at-least-once delivery&lt;/strong&gt;. We either have to be alright with the external service being invoked more than once or the service needs to handle duplicate messages. The latter is, however, a topic for a separate article.&lt;/p&gt;

&lt;h1&gt;
  
  
  Implementation example
&lt;/h1&gt;

&lt;p&gt;I'll create a simple web application to simulate the "welcome email" scenario.&lt;/p&gt;

&lt;p&gt;I'll use Kotlin with Spring to model the application and PostgreSQL as the database. I believe the code samples can be easily translated to other languages and frameworks.&lt;/p&gt;

&lt;p&gt;I chose PostgreSQL since I'm using it for a side project where I've already implemented this pattern and it has proved to be working just fine, so the code listed below is battle-tested. Besides, I'll use a &lt;code&gt;SKIP LOCKED&lt;/code&gt; feature which is specific to PostgreSQL ≥9.5. It is used to lock rows for editing in order to build a concurrent queue. A similar feature should be available at least in Oracle Database and SQL Server&lt;sup id="fnref1"&gt;1&lt;/sup&gt;.&lt;/p&gt;

&lt;p&gt;You can see the complete working implementation @ &lt;a href="https://github.com/maciejtoporowicz/transactional-outbox-example"&gt;https://github.com/maciejtoporowicz/transactional-outbox-example&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We'll need two tables in our database:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;account { id, name, email }
outbox_message { id, type, json_content }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;em&gt;&lt;a href="https://github.com/maciejtoporowicz/transactional-outbox-example/blob/master/schema.sql"&gt;View source code @ GitHub&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;When an account is created, in our business logic we need to create two objects: one for representing the account and another one for representing events related to the account creation. We can then ask our &lt;code&gt;accountRepo&lt;/code&gt; to save both objects at once.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nf"&gt;AccountModule&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt; &lt;span class="nl"&gt;accountRepo:&lt;/span&gt; &lt;span class="nc"&gt;AccountRepo&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;createNewAccount&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nl"&gt;name:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nl"&gt;email:&lt;/span&gt; &lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;val&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;account&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;relatedEvents&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Account&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;newAccount&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;email&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;

        &lt;span class="n"&gt;accountRepo&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;save&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;account&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="n"&gt;relatedEvents&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;em&gt;&lt;a href="https://github.com/maciejtoporowicz/transactional-outbox-example/blob/master/src/main/kotlin/it/toporowicz/outbox/core/account/AccountModule.kt"&gt;View source code @ GitHub&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Here's the implementation of the &lt;code&gt;AccountRepo::save&lt;/code&gt; method with some context:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nf"&gt;AccountRepoAdapter&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
        &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt; &lt;span class="nl"&gt;accountRepo:&lt;/span&gt; &lt;span class="nc"&gt;SpringAccountRepo&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
        &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt; &lt;span class="nl"&gt;outboxMessageRepo:&lt;/span&gt; &lt;span class="nc"&gt;SpringOutboxMessageRepo&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
        &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt; &lt;span class="nl"&gt;jsonMapper:&lt;/span&gt; &lt;span class="nc"&gt;JsonMapper&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;AccountRepo&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Transactional&lt;/span&gt;
    &lt;span class="n"&gt;override&lt;/span&gt; &lt;span class="n"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;save&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nl"&gt;account:&lt;/span&gt; &lt;span class="nc"&gt;Account&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nl"&gt;relatedEvents:&lt;/span&gt; &lt;span class="nc"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;AccountEvent&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;accountRepo&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;save&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;asEntity&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;account&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt;
        &lt;span class="n"&gt;outboxMessageRepo&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;saveAll&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
                &lt;span class="n"&gt;relatedEvents&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;stream&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
                        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;map&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
                            &lt;span class="nc"&gt;OutboxMessage&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;
                                    &lt;span class="n"&gt;eventType&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;it&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;javaClass&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;canonicalName&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt;
                                    &lt;span class="n"&gt;jsonContent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;jsonMapper&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toJson&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;it&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
                            &lt;span class="o"&gt;)&lt;/span&gt;
                        &lt;span class="o"&gt;}&lt;/span&gt;
                        &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;toList&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
        &lt;span class="o"&gt;)&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;em&gt;&lt;a href="https://github.com/maciejtoporowicz/transactional-outbox-example/blob/master/src/main/kotlin/it/toporowicz/outbox/adapter/AccountRepoAdapter.kt"&gt;View source code @ GitHub&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;This is an adapter class between the business logic contained in &lt;code&gt;AccountModule&lt;/code&gt; and the infrastructure-related classes - &lt;code&gt;SpringAccountRepo&lt;/code&gt; and &lt;code&gt;SpringOutboxMessageRepo&lt;/code&gt; which do the actual inserts to the database.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;As you can see, I'm using the canonical name of the class as the &lt;code&gt;OutboxMessage#type&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;With the messages in the database, we can proceed to the polling mechanism. We've got a &lt;code&gt;OutboxMessagePollerTimer&lt;/code&gt; class with a &lt;code&gt;tick()&lt;/code&gt; method running at constant intervals:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Scheduled&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fixedRateString&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s"&gt;"\${outboxMessages.polling.interval}"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;tick&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;info&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Polling for outbox messages"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;taskExecutor&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;execute&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;outboxMessagePollerFactory&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;newOutgoingEventPoller&lt;/span&gt;&lt;span class="o"&gt;())&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;em&gt;&lt;a href="https://github.com/maciejtoporowicz/transactional-outbox-example/blob/master/src/main/kotlin/it/toporowicz/outbox/infrastructure/event/OutboxMessagePollerTimer.kt"&gt;View source code @ GitHub&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The polling interval should be fine tuned to match the requirements and capabilities of the application.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Each time &lt;code&gt;tick()&lt;/code&gt; is invoked, a new task is inserted into a thread pool to poll the &lt;code&gt;outbox_message&lt;/code&gt; table and handle pending outbox messages. Here's the implementation of the task:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="o"&gt;(...)&lt;/span&gt;

&lt;span class="n"&gt;transaction&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;begin&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;

&lt;span class="n"&gt;val&lt;/span&gt; &lt;span class="n"&gt;message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;deleteFirstMessage&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;entityManager&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="kc"&gt;null&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;transaction&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;rollback&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;val&lt;/span&gt; &lt;span class="n"&gt;messageContent&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;extractMessageContentFrom&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;applicationEventPublisher&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;publishEvent&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;messageContent&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;transaction&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;commit&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="o"&gt;(...)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;em&gt;&lt;a href="https://github.com/maciejtoporowicz/transactional-outbox-example/blob/master/src/main/kotlin/it/toporowicz/outbox/infrastructure/event/OutboxMessagePoller.kt"&gt;View source code @ GitHub&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;The published event gets picked up by a &lt;code&gt;WelcomeEmailTrigger&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;WelcomeEmailTrigger&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="n"&gt;val&lt;/span&gt; &lt;span class="n"&gt;log&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;LoggerFactory&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getLogger&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nl"&gt;WelcomeEmailTrigger:&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="kd"&gt;class&lt;/span&gt;&lt;span class="err"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;java&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;

    &lt;span class="nd"&gt;@EventListener&lt;/span&gt;
    &lt;span class="n"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;onAccountCreated&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nl"&gt;event:&lt;/span&gt; &lt;span class="nc"&gt;AccountCreatedEvent&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;log&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;info&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"Received event: $event"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;em&gt;&lt;a href="https://github.com/maciejtoporowicz/transactional-outbox-example/blob/master/src/main/kotlin/it/toporowicz/outbox/delivery/event/account/WelcomeEmailTrigger.kt"&gt;View source code @ GitHub&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;applicationEventPublisher.publishEvent(...)&lt;/code&gt; is synchronous, so it'll return only if all event handlers finish processing the published event. We should be safe to commit the transaction afterwards.&lt;/p&gt;

&lt;h1&gt;
  
  
  Key takeways
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;Transactioncal consistency reduces the availability of your system.&lt;/li&gt;
&lt;li&gt;Do you need transactional consistency?&lt;/li&gt;
&lt;li&gt;Eventual consistency does not mean that your system will be slow. It may often be a matter of milliseconds for it to become consistent.&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Further reading
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.enterpriseintegrationpatterns.com/ramblings/18_starbucks.html"&gt;Starbucks Does Not Use Two-Phase Commit&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.infoq.com/articles/no-reliable-messaging/"&gt;Nobody Needs Reliable Messaging&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://microservices.io/patterns/data/transactional-outbox.html"&gt;Transactional outbox @ microservices.io&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://microservices.io/patterns/data/polling-publisher.html"&gt;Polling publisher @ microservices.io&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://microservices.io/patterns/data/transaction-log-tailing.html"&gt;Transaction log tailing @ microservices.io&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.2ndquadrant.com/en/blog/what-is-select-skip-locked-for-in-postgresql-9-5/"&gt;What is SKIP LOCKED for in PostgreSQL 9.5?&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Sources
&lt;/h1&gt;




&lt;ol&gt;

&lt;li id="fn1"&gt;
&lt;p&gt;&lt;a href="https://www.2ndquadrant.com/en/blog/what-is-select-skip-locked-for-in-postgresql-9-5/"&gt;https://www.2ndquadrant.com/en/blog/what-is-select-skip-locked-for-in-postgresql-9-5/&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;/ol&gt;

</description>
      <category>architecture</category>
      <category>tutorial</category>
      <category>messaging</category>
      <category>kotlin</category>
    </item>
    <item>
      <title>Fake the system clock for a single application with libfaketime</title>
      <dc:creator>Maciej Toporowicz</dc:creator>
      <pubDate>Tue, 17 Mar 2020 20:41:52 +0000</pubDate>
      <link>https://dev.to/maciejtoporowicz/fake-the-system-clock-for-a-single-application-with-libfaketime-4oge</link>
      <guid>https://dev.to/maciejtoporowicz/fake-the-system-clock-for-a-single-application-with-libfaketime-4oge</guid>
      <description>&lt;h1&gt;
  
  
  A bit of a back story
&lt;/h1&gt;

&lt;p&gt;My use case was quite specific - I wanted to conduct some end-to-end tests of a Java app running in a Docker container based on CentOS. The piece of code that I wanted to test was relying on date comparison:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;happenedYesterday&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;event&lt;/span&gt;&lt;span class="o"&gt;))&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;foo&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;bar&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Given that I was not able to modify the test data, the easiest thing was to somehow make the application think it's &lt;em&gt;yesterday&lt;/em&gt;, make it create the&lt;code&gt;event&lt;/code&gt;, then restore the original date and make the application invoke the above piece of code.&lt;/p&gt;

&lt;h1&gt;
  
  
  The setup
&lt;/h1&gt;

&lt;p&gt;Since I would like to show how I got from an idea to a working solution, I need to provide a way to reproduce all the mistakes that I've made as part of this exercise - I need an environment which is as close to the original as possible. To achieve it and also to keep the examples as simple as possible, I'll use &lt;a href="https://hub.docker.com/r/fabric8/java-centos-openjdk8-jdk"&gt;fabric8/java-centos-openjdk8-jdk&lt;/a&gt; Docker image.&lt;/p&gt;

&lt;p&gt;Let's start a container from an unmodified image and open up its shell:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[me@pc ~]$ docker run --name centos -d -it fabric8/java-centos-openjdk8-jdk /bin/bash
...
[me@pc ~]$ docker exec -u 0 -it centos /bin/bash
[root@centos /]#
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;NOTE: &lt;strong&gt;&lt;em&gt;-u 0&lt;/em&gt;&lt;/strong&gt; argument makes the command log into the container as root (0 is root's user id)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In all the examples in this post, I'll use &lt;code&gt;pc&lt;/code&gt; as in &lt;code&gt;[me@pc ~]$&lt;/code&gt; to indicate commands invoked on my local machine and &lt;code&gt;centos&lt;/code&gt; as in &lt;code&gt;[root@centos /]#&lt;/code&gt; for commands invoked inside the container. &lt;/p&gt;

&lt;h1&gt;
  
  
  Setting the system date in Docker - naive approach
&lt;/h1&gt;

&lt;p&gt;In my naive approach, I thought this step would be as simple as running one of these commands:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[root@centos /]# date -s "15 Oct 2019 19:05"
date: cannot set date: Operation not permitted
Tue Oct 15 19:05:00 UTC 2019
[root@centos /]# hwclock --set --date "15 Oct 2019 19:05"
hwclock: Cannot access the Hardware Clock via any known method.
hwclock: Use the --debug option to see the details of our search for an access method.
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Unfortunately, it wasn't.&lt;/p&gt;

&lt;p&gt;I tried to find some workarounds, but as far as I understand, Docker reuses the clock of the host machine, so overriding the date in the container is either not doable or not easily doable&lt;sup id="fnref1"&gt;1&lt;/sup&gt;&lt;sup id="fnref2"&gt;2&lt;/sup&gt;&lt;sup id="fnref3"&gt;3&lt;/sup&gt;. As I'm just a casual user of Docker, I didn't want to dig deeper. However, when looking for the workarounds, I stumbled upon a different way to change the time - &lt;strong&gt;libfaketime&lt;/strong&gt;.&lt;/p&gt;

&lt;h1&gt;
  
  
  libfaketime
&lt;/h1&gt;

&lt;p&gt;libfaketime is a library which is able to 'override' system calls that applications use to retrieve current date or time. It is then able to provide a fake value for these calls. What's more, &lt;strong&gt;you don't have to change a line of your existing code&lt;/strong&gt; or add it to your app's dependency list - it'll be transparent. Since I'm not a Linux guru, using this library at first felt like it was a wrapper for my java application, though it's not how it works.&lt;/p&gt;

&lt;p&gt;The installation is straightforward - you grab the source code of the library and run &lt;code&gt;make install&lt;/code&gt; in the root directory of the checked out sources. It'll result in a bunch of files getting created in &lt;code&gt;/usr/local/lib/faketime&lt;/code&gt;. To automate this process, I created the following Dockerfile:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight docker"&gt;&lt;code&gt;&lt;span class="k"&gt;FROM&lt;/span&gt;&lt;span class="s"&gt; fabric8/java-centos-openjdk8-jdk&lt;/span&gt;

&lt;span class="k"&gt;USER&lt;/span&gt;&lt;span class="s"&gt; root&lt;/span&gt;

&lt;span class="k"&gt;RUN &lt;/span&gt;yum &lt;span class="nt"&gt;-y&lt;/span&gt; groupinstall &lt;span class="s1"&gt;'Development Tools'&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="se"&gt;\
&lt;/span&gt;    yum &lt;span class="nt"&gt;-y&lt;/span&gt; &lt;span class="nb"&gt;install &lt;/span&gt;make unzip wget &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="se"&gt;\
&lt;/span&gt;    &lt;span class="nb"&gt;mkdir &lt;/span&gt;faketime &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="se"&gt;\
&lt;/span&gt;    &lt;span class="nb"&gt;cd &lt;/span&gt;faketime &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="se"&gt;\
&lt;/span&gt;    wget https://github.com/wolfcw/libfaketime/archive/master.zip &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="se"&gt;\
&lt;/span&gt;    unzip master.zip &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="se"&gt;\
&lt;/span&gt;    &lt;span class="nb"&gt;cd &lt;/span&gt;libfaketime-master &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="se"&gt;\
&lt;/span&gt;    make &lt;span class="nb"&gt;install&lt;/span&gt;

&lt;span class="k"&gt;ENTRYPOINT&lt;/span&gt;&lt;span class="s"&gt; /bin/bash&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Now, it should be possible to start it all up and test the library:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[me@pc ~]$ docker build -t centos .
...
[me@pc ~]$ docker run --name centos -d -it centos /bin/bash
...
[me@pc ~]$ docker exec -u 0 -it centos /bin/bash
[root@centos /]# date
Wed Feb 19 17:16:34 UTC 2020
[root@centos /]# LD_PRELOAD=/usr/local/lib/faketime/libfaketime.so.1 FAKETIME="-15d" date
Tue Feb  4 17:16:49 UTC 2020
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;With the path to libfaketime provided in the &lt;code&gt;LD_PRELOAD&lt;/code&gt; variable, the &lt;code&gt;FAKETIME&lt;/code&gt; variable set to &lt;em&gt;-15 days&lt;/em&gt;, the invocation of &lt;code&gt;date&lt;/code&gt; rendered a date 15 days in the past. To me, the most interesting bit is the &lt;code&gt;LD_PRELOAD&lt;/code&gt; part.&lt;/p&gt;

&lt;h1&gt;
  
  
  LD_PRELOAD variable and the preloading mechanism
&lt;/h1&gt;

&lt;p&gt;The &lt;code&gt;LD_PRELOAD&lt;/code&gt; variable allows to specify paths to libraries which are to be loaded &lt;strong&gt;before&lt;/strong&gt; any other libraries are loaded. What's important, all the symbols (e.g. functions) contained in the preloaded libraries &lt;strong&gt;take precedence&lt;/strong&gt; over the symbols from libraries loaded afterwards&lt;sup id="fnref4"&gt;4&lt;/sup&gt;&lt;sup id="fnref5"&gt;5&lt;/sup&gt;&lt;sup id="fnref6"&gt;6&lt;/sup&gt;.&lt;/p&gt;

&lt;p&gt;It means that if a program uses a function &lt;code&gt;foo()&lt;/code&gt; from library &lt;strong&gt;A&lt;/strong&gt; and library &lt;strong&gt;A&lt;/strong&gt; is linked at runtime, it is possible to provide a path to library &lt;strong&gt;B&lt;/strong&gt; containing a different implementation of &lt;code&gt;foo()&lt;/code&gt; in the &lt;code&gt;LD_PRELOAD&lt;/code&gt; variable. As a result, when the program references &lt;code&gt;foo()&lt;/code&gt; in its source code, the implementation from library &lt;strong&gt;B&lt;/strong&gt; will be invoked.&lt;/p&gt;

&lt;p&gt;libfaketime replaces the symbols related to interactions with the system clock using the preloading mechanism.&lt;/p&gt;

&lt;p&gt;Given all the knowledge gathered so far, it's time to fake the date in a Java app.&lt;/p&gt;

&lt;h1&gt;
  
  
  Setting a fake date for a Java app
&lt;/h1&gt;

&lt;p&gt;First of all - to test the library, I created a simple application that prints the current date and time each second, forever. Here's the code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.time.LocalDateTime&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.concurrent.Executors&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;
&lt;span class="kn"&gt;import&lt;/span&gt; &lt;span class="nn"&gt;java.util.concurrent.TimeUnit&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Main&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
  &lt;span class="kd"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="no"&gt;NO_DELAY&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt;

  &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;static&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;String&lt;/span&gt;&lt;span class="o"&gt;[]&lt;/span&gt; &lt;span class="n"&gt;args&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;Runnable&lt;/span&gt; &lt;span class="n"&gt;printCurrentDateTime&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;out&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;println&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;LocalDateTime&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;now&lt;/span&gt;&lt;span class="o"&gt;());&lt;/span&gt;

    &lt;span class="nc"&gt;Executors&lt;/span&gt;
      &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;newSingleThreadScheduledExecutor&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt;
      &lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;scheduleAtFixedRate&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;printCurrentDateTime&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="no"&gt;NO_DELAY&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;TimeUnit&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;SECONDS&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
  &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Then, to test the library with the application, I ran the CentOS container again with a volume set to the directory where the java class was.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[me@pc ~]$ docker run --name centos -v /home/test/:/app -d -it centos /bin/bash
...
[me@pc ~]$ docker exec -u 0 -it centos /bin/bash
[root@centos /]# cd /app
[root@centos app] javac Main.java
[root@centos app] java Main
2020-02-20T21:53:36.132
2020-02-20T21:53:37.113
2020-02-20T21:53:38.113
^C
[root@centos app] LD_PRELOAD=/usr/local/lib/faketime/libfaketime.so.1 FAKETIME="-15d" FAKETIME_DONT_FAKE_MONOTONIC=1 java Main
2020-02-05T21:55:51.787
2020-02-05T21:55:52.766
2020-02-05T21:55:53.765
^C
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;It's working as expected, though I added another variable to the command: &lt;code&gt;FAKETIME_DONT_FAKE_MONOTONIC=1&lt;/code&gt;. From the &lt;a href="https://github.com/wolfcw/libfaketime"&gt;README of libfaketime&lt;/a&gt;:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Java-/JVM-based applications work but you need to pass in an extra argument&lt;br&gt;
  (FAKETIME_DONT_FAKE_MONOTONIC).  See usage basics below for details.  Without&lt;br&gt;
  this argument the java command usually hangs.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Indeed, without it even this tiny program hanged after printing the first date. I must admit I wasted some time debugging it just because I skipped reading the readme.&lt;/p&gt;

&lt;h1&gt;
  
  
  Cleaning it up
&lt;/h1&gt;

&lt;p&gt;To shorten the commands, &lt;code&gt;LD_PRELOAD&lt;/code&gt; and &lt;code&gt;FAKETIME_DONT_FAKE_MONOTONIC&lt;/code&gt; values can be specified as the environment values of the Docker image. I omitted &lt;code&gt;FAKETIME&lt;/code&gt; because this one is likely to change.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight docker"&gt;&lt;code&gt;...

&lt;span class="k"&gt;USER&lt;/span&gt;&lt;span class="s"&gt; root&lt;/span&gt;

&lt;span class="k"&gt;ENV&lt;/span&gt;&lt;span class="s"&gt; LD_PRELOAD /usr/local/lib/faketime/libfaketime.so.1&lt;/span&gt;
&lt;span class="k"&gt;ENV&lt;/span&gt;&lt;span class="s"&gt; FAKETIME_DONT_FAKE_MONOTONIC 1&lt;/span&gt;

&lt;span class="k"&gt;RUN &lt;/span&gt;...
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;After these changes, it should be possible to run &lt;code&gt;FAKETIME="-15d" java Main&lt;/code&gt; to render the same output as before. &lt;/p&gt;

&lt;h1&gt;
  
  
  Changing the time dynamically at runtime
&lt;/h1&gt;

&lt;p&gt;It is possible to specify the &lt;code&gt;FAKETIME&lt;/code&gt; value in a file instead of a variable. It makes it possible to change the value at any moment. libfaketime will pick it up after ten seconds&lt;sup id="fnref7"&gt;7&lt;/sup&gt;.&lt;/p&gt;

&lt;p&gt;It is possible to do this system-wide or just for a user. I'll describe the latter.&lt;/p&gt;

&lt;p&gt;The file needs to be named &lt;code&gt;.faketimerc&lt;/code&gt; and it needs to be placed in the home directory. It should contain only the value of the &lt;code&gt;FAKETIME&lt;/code&gt; variable, just like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-15d
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;Running &lt;code&gt;java Main&lt;/code&gt; in the shell should now render the expected output. While the program running keeps running, in another shell session we can type &lt;code&gt;echo -10d &amp;gt; ~/.faketimerc&lt;/code&gt;. The output should change after ten seconds.&lt;/p&gt;

&lt;h1&gt;
  
  
  Different variants of the FAKETIME value
&lt;/h1&gt;

&lt;p&gt;Specifying a relative offset is not the only way to fake the time. Here are some more variants:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;different offset mutlipliers: all the examples used "-16d", but instead of "d" it can also be "m", "h", "y" or nothing for seconds; the offset can be set in the past (&lt;code&gt;-10d&lt;/code&gt;) or in the future (&lt;code&gt;+10d&lt;/code&gt;) 
&amp;gt; EXAMPLES:
&amp;gt;  * &lt;code&gt;-120&lt;/code&gt; is 120 seconds behind
&amp;gt;  * &lt;code&gt;+2h&lt;/code&gt; is 2 hours in the future
&amp;gt;  * &lt;code&gt;+1y&lt;/code&gt; is 1 year in the future&lt;/li&gt;
&lt;li&gt;'start at' date: &lt;code&gt;FAKETIME="@2020-12-24 20:30:00"&lt;/code&gt;, where the clock will start ticking from this date &lt;strong&gt;for each new process&lt;/strong&gt;, but it's possible to configure it to keep the clock ticking instead&lt;sup id="fnref7"&gt;7&lt;/sup&gt;
&lt;/li&gt;
&lt;li&gt;absolute date: &lt;code&gt;FAKETIME="2020-12-24 20:30:00"&lt;/code&gt; will render a fixed value, as if the time stopped at this point&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Summary
&lt;/h1&gt;

&lt;p&gt;These are not all the features that libfaketime supports. I suggest skimming through the list of features in the readme just to get familiar with the possiblities - just in case you ever need to use any of them.&lt;/p&gt;

&lt;h1&gt;
  
  
  Key takeways
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;I'll use libfaketime in cases similar to this one&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;LD_PRELOAD&lt;/code&gt; mechanism can be used on Linux machines to replace pieces of code without modifying the original code&lt;/li&gt;
&lt;li&gt;I should have read the friendly manual earlier to save time&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Further reading
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/wolfcw/libfaketime"&gt;libfaketime manual - GitHub&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="http://www.goldsborough.me/c/low-level/kernel/2016/08/29/16-48-53-the_-ld_preload-_trick/"&gt;The LD_PRELOAD trick&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://blog.fpmurphy.com/2012/09/all-about-ld_preload.html"&gt;All about LD_PRELOAD&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://rafalcieslak.wordpress.com/2013/04/02/dynamic-linker-tricks-using-ld_preload-to-cheat-inject-features-and-investigate-programs/"&gt;Dynamic linker tricks: Using LD_PRELOAD to cheat, inject features and investigate programs&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;
  
  
  Sources
&lt;/h1&gt;




&lt;ol&gt;

&lt;li id="fn1"&gt;
&lt;p&gt;&lt;a href="https://forums.docker.com/t/is-it-possible-to-change-time-dynamically-in-docker-container/56787/5"&gt;https://forums.docker.com/t/is-it-possible-to-change-time-dynamically-in-docker-container/56787/5&lt;/a&gt;  ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn2"&gt;
&lt;p&gt;&lt;a href="https://forums.docker.com/t/change-containers-year/58880/3"&gt;https://forums.docker.com/t/change-containers-year/58880/3&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn3"&gt;
&lt;p&gt;&lt;a href="https://stackoverflow.com/a/29561602"&gt;https://stackoverflow.com/a/29561602&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn4"&gt;
&lt;p&gt;&lt;a href="http://www.goldsborough.me/c/low-level/kernel/2016/08/29/16-48-53-the_-ld_preload-_trick/"&gt;http://www.goldsborough.me/c/low-level/kernel/2016/08/29/16-48-53-the_-ld_preload-_trick/&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn5"&gt;
&lt;p&gt;&lt;a href="https://blog.fpmurphy.com/2012/09/all-about-ld_preload.html"&gt;https://blog.fpmurphy.com/2012/09/all-about-ld_preload.html&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn6"&gt;
&lt;p&gt;&lt;a href="https://rafalcieslak.wordpress.com/2013/04/02/dynamic-linker-tricks-using-ld_preload-to-cheat-inject-features-and-investigate-programs/"&gt;https://rafalcieslak.wordpress.com/2013/04/02/dynamic-linker-tricks-using-ld_preload-to-cheat-inject-features-and-investigate-programs/&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;li id="fn7"&gt;
&lt;p&gt;&lt;a href="https://github.com/wolfcw/libfaketime"&gt;https://github.com/wolfcw/libfaketime&lt;/a&gt; ↩&lt;/p&gt;
&lt;/li&gt;

&lt;/ol&gt;

</description>
      <category>tutorial</category>
      <category>docker</category>
      <category>java</category>
      <category>testing</category>
    </item>
  </channel>
</rss>
