<?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 Bijil Abraham on Medium]]></title>
        <description><![CDATA[Stories by Bijil Abraham on Medium]]></description>
        <link>https://medium.com/@bijilap2?source=rss-f55abd4cca78------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Pm-iCXBKT0rOrNmY.</url>
            <title>Stories by Bijil Abraham on Medium</title>
            <link>https://medium.com/@bijilap2?source=rss-f55abd4cca78------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 01:33:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bijilap2/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[Layered Architecture in Practice]]></title>
            <link>https://medium.com/@bijilap2/layered-architecture-in-practice-9e959d75ef77?source=rss-f55abd4cca78------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e959d75ef77</guid>
            <category><![CDATA[code-architecture]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[layered-architecture]]></category>
            <dc:creator><![CDATA[Bijil Abraham]]></dc:creator>
            <pubDate>Thu, 22 Dec 2022 13:24:49 GMT</pubDate>
            <atom:updated>2022-12-22T13:24:49.633Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y6dy73fMoFMlP-Cx.jpg" /><figcaption>Illustration 1: Layers of the Earth (Source: <a href="https://www.worldatlas.com/">https://www.worldatlas.com/</a>)</figcaption></figure><h3>Introduction</h3><p>We live in the era of microservices (or services with a single responsibility). Whether that is the right pattern is a topic for another day. The first question that comes to my mind whenever I need to create a new service or shared library is: “How do I organize my code” ? This question is harder than you would expect.</p><p>Every service is simple and comprehensible in the beginning. But businesses (especially web-based) are seldom static. Changing requirements introduce complexity to service code. A well written service or library is one that can stand the test of time.</p><p>A lot of books and blogs have been written proposing different ideas around code architecture. Here are some that I found helpful:</p><ul><li><a href="https://alistair.cockburn.us/hexagonal-architecture/">Hexagonal Architecture (a.k.a. Ports and Adapters) by Alistair Cockburn</a></li><li><a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">Clean Architecture by Robert C Martin</a></li><li><a href="https://jeffreypalermo.com/2008/07/the-onion-architecture-part-1/">Onion Architecture by Jeffrey Palermo</a></li></ul><p>In this article I will walk you through a layered architecture that has helped me and my team(s) create services that have been able to adapt to changing requirements. You will see this code architecture is clearly inspired by the three blogs mentioned above.</p><h3>Use case study</h3><p>Let’s look at a sample use case to understand layered code architecture and its benefits. Imagine that you are building an app that allows users to book hotel rooms. Assume that there is a microservice that provides APIs to reserve a room, and finalize room booking after payment.</p><p>Flow of control for booking a room</p><ul><li>Block a room that matches the type of room selected by the user. Deluxe, queen are some type of rooms</li><li>Direct user to checkout using PayPal or Amazon Pay or any other payment provider supported by the platform</li><li>Call payment provider’s backend API to charge user based on order reference id</li><li>Call the hotel management service provider’s APIs to finalize booking</li><li>Execute operations to wrap up room booking:<br> . Send email to customer with details of the room booking<br> . Store success response and booking details for idempotency<br> . Respond to user with success</li></ul><p>Let’s look at some bare bones code to implement backend microservice for this.</p><pre>@AllArgsConstructor(onConstructor = @__(@Inject))<br>class RoomBookingController {<br><br>  private final InitiateRoomBookingStep initiateRoomBookingStep;<br><br>  private final CompleteRoomBookingStep completeRoomBookingStep<br><br>  @PostMapping(&quot;/v1/room-booking&quot;)<br>  public RoomBooking initateRoomBooking(@RequestBody RoomBooking roomBookingRequest) {<br>    try {<br>       return initiateRoomBookingStep.execute(roomBookingRequest);<br>    }<br>    catch(Exception e){<br>      // handle exception and return corresponding error responses<br>    }<br>  }<br>  <br>  @PostMapping(&quot;/v1/room-booking/{bookingId}/complete&quot;)<br>  public PaymentContext completeRoomBooking(@PathVariable(&quot;bookingId&quot;) String bookingId, @RequestBody PaymentContext paymentContext) {<br>    try {<br>       return completeRoomBookingStep.execute(bookingId, paymentContext);<br>    }<br>    catch(Exception e){<br>      // handle exception and return corresponding error responses<br>    }<br>  }<br>}</pre><pre>// To be called from API to initiate room booking<br>@AllArgsConstructor(onConstructor = @__(@Inject))<br>class InitiateRoomBookingStep {<br><br>  private final CoruscantHotelAccessor coruscantHotelAccessor;<br><br>  private final DynamoDBAccessor dynamoDBAccessor;<br><br>  public RoomBooking execute(RoomBooking roomBookingRequest) {<br>    BlockHotelRoomRequest blockHotelRoomRequest = mapBlockHotelRoomRequest(roomBookingRequest);<br>    BlockHotelRoomResult blockHotelRoomResult = coruscantHotelAccessor.blockHotelRoom(blockHotelRoomRequest);<br>    dynamoDBAccessor.storeRoomBookingRecord(blockHotelRoomRequest, blockHotelRoomResult);<br><br>    return buildRoomBookingResponse(roomBookingRequest, blockHotelRoomResult.getBookingId());<br>  }<br><br>  private BlockHotelRoomRequest mapBlockHotelRoomRequest(RoomBooking roomBookingRequest) {<br>    // logic to map RoomBooking to BlockHotelRoomRequest<br>  }<br><br>  private RoomBooking buildRoomBookingResponse(RoomBooking roomBookingRequest, String hotelBookingId) {<br>    // logic to create RoomBooking response<br>  }<br><br>}</pre><pre>@AllArgsConstructor(onConstructor = @__(@Inject))<br>public CompleteRoomBookingStep {<br><br>  private final CoruscantHotelAccessor coruscantHotelAccessor;<br><br>  private final DynamoDBAccessor dynamoDBAccessor;<br><br>  private final PayPalAccessor payPalAccessor;<br><br>  public PaymentContext execute(String bookingId, PaymentContext paymentContext) {<br>    // Check if room booking was already complete<br>    // Call payment completion api<br>    // Persist details about successful payment<br>    // Finalise room booking<br>    // Update order details in database<br><br>    RoomBookingRecord bookingRecord = dynamoDBAccessor.retrieveRoomBookingRecord(bookingId);<br>    PaymentContext updatedPaymentContext = payPalAccessor.createOrder(paymentContext);<br>    RoomBookingRecord updatedBookingRecord  = new RoomBookingRecord(bookingRecord);<br>    // Code for mapping fields from updatedPaymentContext to updatedBookingRecord<br>    dynamoDBAccessor.storeRoomBookingRecord(updatedPaymentContext);<br>    return updatedPaymentContext;<br>  }<br>}</pre><pre>@AllArgsConstructor(onConstructor = @__(@Inject))<br>class CoruscantHotelAccessor {<br><br>  public BlockHotelRoomResult blockHotelRoom (BlockHotelRoomRequest request) {<br>    // POST /hotelRoomBooking<br>  }<br>  <br>  public FinaliseRoomBookingResult finaliseRoomBooking (FinaliseRoomBookingRequest request) {<br>    // POST /hotelRoomBooking/&lt;roomId&gt;/finalise<br>  }<br><br>}</pre><pre>@AllArgsConstructor(onConstructor = @__(@Inject))<br>class PayPalAccessor {<br><br>  private final HttpClient httpClient;<br><br>  public PaymentContext createOrder(PaymentContext paymentContext) {<br>    String request = mapOrderRequest(paymentContext);<br>    HttpRequest request = HttpRequest.newBuilder()<br>     .POST(HttpRequest.BodyPublishers.ofString(orderPayload))<br>     .uri(URI.create(&quot;/v2/checkout/orders&quot;))<br>     .header(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>     .build();<br>    HttpResponse&lt;Order&gt; response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());<br>    // publish operational metrics<br>    return processOrderResponse(response, paymentContext);<br>  }<br><br>  private String mapOrderRequest(PaymentContext paymentContext) {<br>     // logic to map Order request payload<br>  }<br><br>  private PaymentContext processOrderResponse(HttpResponse&lt;Order&gt; response, PaymentContext paymentContext) {<br>    ...<br>  }<br>}</pre><pre>@AllArgsConstructor(onConstructor = @__(@Inject))<br>class DynamoDBAccessor {<br><br>  private final DynamoDBMapper dynamoDBMapper;<br><br>  public void storeRoomBookingRecord(RoomBooking roomBookingRequest, BlockHotelRoomResult blockHotelRoomResult) {<br>    RoomBookingRecord roomBookingRecord = mapRoomBookingRecord(roomBookingRequest, blockHotelRoomResult);<br>    dynamoDBMapper.save(roomBookingRecord);<br>  }<br><br>  public void updateRoomBookingRecord(RoomBookingRecord roomBookingRecord) {<br>      // store in dynamodb<br>  }<br><br>  public RoomBookingRecord retrieveRoomBookingRecord(String bookingId) {<br>    return storeRoomBookingRecord.load(RoomBookingRecord.class, bookingId);<br>  }<br><br>  private RoomBookingRecord mapRoomBookingRecord(RoomBooking roomBookingRequest, BlockHotelRoomResult blockHotelRoomResult) {<br>    // logic to map RoomBookingRecord from roomBookingRequest and blockHotelRoomResult<br>  }<br>}</pre><p><em>Note: As of November 2022, `@__(@Inject)` is still experimental</em>.</p><p>This fairly decent code gets the job done. But there are a few problems with this code:</p><ul><li>Strong coupling with dependencies: The business logic here is tightly coupled with the dependency service / technology used. For example: if something changes in Coruscant’s or PayPal’s APIs, it will directly effect the business logic.</li><li>Code is platform dependent: The business logic is heavily dependent on the underlying protocol used (RCP vs REST ), compute platform used (containers vs Faas) and database solution used. Any change in any of them will add to the business logic.</li><li>Difficult to unit test business logic: Since business logic is not insulated, it is hard to write unit tests that only test the service’s business logic.</li></ul><h3>Layered Architecture</h3><p>Now let’s look at a layered code architecture that will help alleviate the problems discussed above. The main idea is to organize code in such a way it is extensible, flexible and insulated from external changes. In this code architecture, the classes / modules can be organized into three layers:</p><ol><li><strong>Framework Layer</strong><br>This is the layer that interacts with the outside world. It contains controllers (to host APIs) and accessors (to call dependency services). <br>If needed it can also include POJOs to represent request and response objects of the service’s APIs and downstream services.</li><li><strong>Middleware Layer</strong><br>This layer is responsible for orchestrating between framework and domain layer. It has knowledge of what happens in the layer above and below it.</li><li><strong>Business Logic Layer</strong><br>This is your business logic. This contains the core logic of your service. Your core logic will not change regardless of which downstream service you call or how your service is hosted. It has no knowledge of the framework layer.</li></ol><p>Let’s look at how the above code will change after incorporating layered architecture.</p><pre>@AllArgsConstructor(onConstructor = @__(@Inject))<br>class RoomBookingController {<br><br>  private final RoomBookingHandler roomBookingHandler;<br><br>  @PostMapping(&quot;/v1/room-booking&quot;)<br>  public RoomBooking initateRoomBooking(@RequestBody RoomBooking roomBookingRequest) {<br>    try {<br>      RoomBooking roomBooking = roomBookingHandler.initateRoomBooking(roomBookingRequest);<br>      // emit operational metrics related to success scenarios<br>      return roomBooking;<br>    }<br>    catch(Exception e){<br>      // handle exception and return corresponding error responses<br>      // emit operational metrics for error scenarios (fault and business errors)<br>    }<br>  }<br>  <br>  @PostMapping(&quot;/v1/room-booking/{bookingId}/complete&quot;)<br>  public PaymentContext completeRoomBooking(@PathVariable(&quot;bookingId&quot;) String bookingId, @RequestBody PaymentContext paymentContext) {<br>    try {<br>       PaymentContext updatedPaymentContext = roomBookingHandler.completeRoomBooking(bookingId, paymentContext);<br>       // emit operational metrics related to success scenarios<br>       return updatedPaymentContext;<br>    }<br>    catch(Exception e){<br>      // handle exception and return corresponding error responses<br>      // emit operational metrics for error scenarios (fault and business errors)<br>    }<br>  }<br>}</pre><pre>class RoomBookingHandler {<br><br>  private RoomBookingContextMapper contextMapper;<br><br>  private RoomBookingResponseMapper responseMapper;<br><br>  private InitiateRoomBookingStep initiateRoomBookingStep;<br><br>  private CompleteRoomBookingStep completeRoomBookingStep;<br><br><br> public RoomBooking initateRoomBooking(RoomBooking roomBookingRequest) {<br>   RoomBookingContext roomBookingContext = contextMapper.mapRoomBookingContext(roomBookingRequest);<br>   RoomBookingContext updatedBookingContext = initiateRoomBookingStep.execute(roomBookingContext);<br>   return responseMapper.mapRoomBooking(roomBookingContext);<br> }<br><br><br> public PaymentContext completeRoomBooking (String bookingId, PaymentContext paymentContext) {<br>    RoomBookingContext bookingContext = contextMapper.mapRoomBookingContext(bookingId, roomBookingRequest);<br>    RoomBookingContext updatedBookingContext = completeRoomBookingStep.execute(bookingContext);<br>    return responseMapper.mapPaymentContext(updatedBookingContext);<br> }<br><br>}</pre><pre>interface IContext {<br>  ...<br>}<br><br><br>class RoomBookingContext implements IContext{<br>  ...<br>  private String bookingId;<br>  private String externalBookingId;<br>  ...<br>}<br><br>class CompleteRoomBookingContext implements IContext{<br>  ...<br>  private String bookingId;<br>  private String externalPaymentReferenceId;<br>  ...<br>}<br><br><br>@AllArgsConstructor(onConstructor = @__(@Inject))<br>class InitiateRoomBookingStep {<br><br>  private final HotelServicesAdapter hotelServicesAdapter;<br><br>  private final BookingStoreAdapter bookingStoreAdapter;<br><br>  public RoomBookingContext execute(RoomBookingContext roomBookingContext) {<br>    RoomBookingContext updatedBookingContext = hotelServicesAdapter.initiateReservation(roomBookingContext);<br>    bookingStoreAdapter.saveRoomBookingContext(updatedBookingContext);<br><br>    return updatedBookingContext;<br>  }<br><br>}<br><br><br>@AllArgsConstructor(onConstructor = @__(@Inject))<br>class CompleteRoomBookingStep {<br><br>  private final PaymentAdapter paymentAdapter;<br><br>  private final IHotelServicesAdapter hotelServicesAdapter;<br><br>  private final BookingStoreAdapter bookingStoreAdapter;<br><br>  public RoomBookingContext execute(RoomBookingContext inputBookingContext) {<br>    String bookingId = bookingContext.getBookingId();<br>    RoomBookingContext originalBookingContext = bookingStoreAdapter.retrieveRoomBookingContext(bookingId);<br>    RoomBookingContext resultBookingContext = new RoomBookingContext(originalBookingContext);<br>    PaymentContext paymentContext = paymentAdapter.completePayment(bookingContext);<br>    result.putPaymentContext(paymentContext);<br>    bookingStoreAdapter.saveRoomBookingContext(resultBookingContext);<br>    return resultBookingContext;<br>  }<br><br>}</pre><pre>interface IPaymentAdapter {<br>  PaymentContext completePayment(RoomBookingContext bookingContext);<br>}<br><br>@AllArgsConstructor(onConstructor = @__(@Inject))<br>class PaymentAdapter implements IPaymentAdapter{<br><br>  private final PayPalRequestMapper paypalRequestMapper;<br><br>  private final PayPalAccessor payPalAccessor;<br><br>  private final PayPalResponseTranslator paypalResponseTranslator;<br><br>  public PaymentContext completePayment(RoomBookingContext bookingContext) {<br>    String orderRequestPayload = paypalRequestMapper.mapOrderRequest(bookingContext);<br>    HttpResponse&lt;Order&gt; orderResponse = payPalAccessor.createOrder(orderRequestPayload);<br>    validateResponse(orderResponse);<br>    return paypalResponseTranslator.translate(orderResponse);<br>  }  <br><br>  private void validateResponse(HttpResponse&lt;Order&gt; orderResponse) {<br>    // analyse http status and error object in response payload<br>    // throw exception in case there an error payload or status code<br>  }<br><br>}<br><br><br>interface IHotelServicesAdapter {<br>  void initiateReservation(RoomBookingContext roomBookingContext);<br>}<br><br>@AllArgsConstructor(onConstructor = @__(@Inject))<br>class HotelServicesAdapter implements IHotelServicesAdapter {<br><br>  private final CoruscantHotelAccessor coruscantHotelAccessor;<br><br>  private final CoruscantHotelPayloadTranslator payloadTranslator;<br><br>  public void initiateReservation(RoomBookingContext roomBookingContext) {<br><br>    try {<br>      BlockHotelRoomRequest blockHotelRoomRequest = payloadTranslator.mapBlockHotelRoomRequest(roomBookingContext);<br>      BlockHotelRoomResult blockHotelRoomResult = coruscantHotelAccessor.blockHotelRoom(blockHotelRoomRequest);<br>      ...<br>      // validate blockHotelRoomResult<br>      ...<br>      roomBookingContext.setStatus(BookingStatus.INITIATED);<br><br>    } catch(RoomNotAvailableException rnaException){<br>       <br>    } catch(Exception e){<br>    }<br>  }<br><br>  public void completeReservation(RoomBookingContext bookingContext) {<br><br>    try {<br>      FinaliseHotelRoomRequest finaliseHotelRoomRequest = payloadTranslator.mapFinaliseHotelRoomRequest(roomBookingContext);<br>      FinaliseHotelRoomResult finaliseHotelRoomResult = coruscantHotelAccessor.finaliseRoomBooking(finaliseHotelRoomRequest);<br>      ...<br>      // validate finaliseHotelRoomResult<br>      ...<br>      roomBookingContext.setStatus(BookingStatus.COMPLETED);<br>    } catch(RoomNotAvailableException rnaException){<br>       <br>    } catch(Exception e){<br>    }<br>  }<br>}<br><br><br>@AllArgsConstructor(onConstructor = @__(@Inject))<br>class BookingStoreAdapter {<br><br>  private BookingStoreRecordTranslator recordTranslator;<br><br>  private DynamoDBAccessor dynamoDBAccessor;<br><br>  public void saveRoomBookingContext(RoomBookingContext roomBookingContext) {<br>    try {<br>      RoomBookingRecord roomBookingRecord = recordTranslator.translateTo(roomBookingContext);<br>      dynamoDBAccessor.putRecord(roomBookingRecord);<br>    } catch(...) {<br>        // Throw exception defined in business-logic layer<br>    }<br>  }<br><br>  public RoomBookingContext retrieveRoomBookingContext(String bookingId) {<br>    try {<br>    } catch(...) {<br>      // Throw exception defined in business-logic layer<br>    }<br>  }<br>}</pre><pre><br>@AllArgsConstructor(onConstructor = @__(@Inject))<br>class PayPalAccessor {<br><br>  private final HttpClient httpClient;<br><br>  public String createOrder(String orderPayload) {<br>    HttpRequest request = HttpRequest.newBuilder()<br>     .POST(HttpRequest.BodyPublishers.ofString(orderPayload))<br>     .uri(URI.create(&quot;/v2/checkout/orders&quot;))<br>     .header(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>     .build();<br>    HttpResponse&lt;Order&gt; response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());<br>    // publish operational metrics<br>    return response;<br>  }<br>}<br><br><br><br>@AllArgsConstructor(onConstructor = @__(@Inject))<br>class CoruscantHotelAccessor {<br><br>  // Client provide by Coruscant Hotel Java SDK<br>  private final CoruscantHotelClient hotelClient;<br><br>  public BlockHotelRoomResult blockHotelRoom (BlockHotelRoomRequest request) {<br>    // Call POST /hotelRoomBooking<br>    // publish operational metrics<br>  }<br>  <br>  public FinaliseHotelRoomResult finaliseRoomBooking (FinaliseHotelRoomRequest request) {<br>    // Call POST /hotelRoomBooking/&lt;roomId&gt;/finalise<br>    // publish operational metrics<br>  }<br><br>}<br><br><br>@AllArgsConstructor(onConstructor = @__(@Inject))<br>class DynamoDBAccessor {<br><br>  private final DynamoDBMapper dynamoDBMapper;<br><br>  public &lt;T&gt; void putRecord(T record) {<br>    dynamoDBMapper.save(record);<br>    // publish operational metrics<br>  }<br><br>  public void updateRecord() {<br>  }  <br><br>  public &lt;T&gt; T getRecord(IStoreKey key, Class&lt;T&gt; type) {<br>  }<br>}</pre><h4>Layers and classes summarized</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3aea5503e6f840dbdbe6359442b0bb44/href">https://medium.com/media/3aea5503e6f840dbdbe6359442b0bb44/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_R1RRtLseWW7TtfCJW_GnA.png" /><figcaption>Illustration 3: Putting the pieces together in a Layered Architecture</figcaption></figure><h3>Adapting to Change</h3><p>Let’s look at how we can adapt the service code to changing requirements.</p><h4><strong>Example 1</strong></h4><p>In the above example, we defined a traditional instance (EC2) / container (ECS) based REST service. Let’s say that your team decides to change the compute platform to API Gateway + AWS Lambda (FaaS) to make use of the auto scaling and serverless features.</p><pre>@AllArgsConstructor(onConstructor = @__(@Inject))<br>public class InitiateRoomBookingEventHandler implements RequestStreamHandler {<br>  <br>  private final Gson gson;<br><br>  private final RoomBookingHandler roomBookingHandler;<br><br>  @Override<br>  public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context) throws IOException {<br>    try {<br>      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(&quot;US-ASCII&quot;)));<br>      RoomBooking roomBookingRequest = gson.fromJson(reader, RoomBooking.class);<br>      RoomBooking roomBookingResponse = roomBookingHandler.initateRoomBooking(roomBookingRequest);<br>      writer.write(gson.toJson(roomBookingResponse));<br>    } catch (Exception e) {<br>       // build response for exception case<br>    }<br>  }<br>}</pre><p>Similarly, you can have another handler for completing the room booking or use the same handler with some event routing logic.</p><p>Thats it!</p><h4><strong>Example 2</strong></h4><p>Let’s say that your application because viral and now you need to onboard more hotels and hotel chains to your application. To support this, assume that you create a microservice to manage interactions with different hotel service providers.</p><p>We have two options:</p><ul><li>Modify the existing HotelServicesAdapter</li><li>Create a new implementation of IHotelServicesAdapter</li></ul><p>Besides the adapter, we will need to define a accessor for the new service, request mapper and translators. Changes to domain layer will be minimal.</p><h4><strong>Example 3</strong></h4><p>Assume that there is a new requirement for you allow room booking only if the hotel / hotel chain has good standing with your company (no negative balance, suspected fraud, etc). The merchants that are deny-listed can be stored in a configuration. The denylist is frequently updated to keep track of changing circumstances.</p><p>We need to do the follow:</p><ul><li>Pick your favorite solution for hosting and managing configuration (object store like S3 or database or serverless config management like AWS AppConfig).</li><li>Write an accessor to invoke the APIs of the config solution</li><li>Create an adapter for configuration</li></ul><p>Here are some pros and cons of this layered architecture:</p><h4>Pros</h4><ul><li><strong>Testability</strong>: Since all the classes have a single responsibility, it makes it easy to unit test every class. A thumb rule would be to mock the dependencies of a class to test and validate it’s behavior. Integration tests are often flaky because of flaky behavior of downstream services in pre-production environments. With a layered architecture, you can have stable functional tests that test the business logic by mocking the accessors defined in the framework layer.</li><li><strong>Freedom from platform lock-in</strong>: This layered architecture lends itself well for experimentation and trying out new things. For example, you can start building your application using AWS Lambda (FaaS) and migrate to something like ECS when latency and cost management becomes critical. Similarly you can bootstrap your application using your favorite database solution (Postgres, MongoDB, etc) and then migrate to an internet-scale solution like DynamoDB.</li><li><strong>Isolation from external changes</strong>: Since the code is organized in layers, changes in dependencies will be limited to the framework layer (and sometimes till middleware layer). The business logic will not have to change when a dependency changes or we decide to alter the dependency used.</li></ul><h4>Cons</h4><ul><li><strong>Slows down implementation</strong>: Using layered architecture takes longer to implement. The main reason is that there is a lot more code to write (lots of classes with well defined single responsibility).</li><li><strong>Requires careful thought</strong>: Layered architecture can easily be misunderstood. We can easily end up with too many redundant classes. A tell-tell way to identify this when there are multiple classes that just call translate data from one entity to another; or have classes with methods that just call methods of another class and don’t have any logic in them.</li></ul><h3>Conclusion</h3><p>A well written service or library that leverages layered code architecture can stand the test of time while catering to changing requirements and changing downstream dependencies. It can facilitate experimentation and enable <a href="https://shit.management/one-way-and-two-way-door-decisions/">two-way door decisions</a>. While layered architectures can seem complex at first, they become easy to extend, manage and reduce complexity in the long run. But do keep in mind that Layered Architecture is not the silver bullet for all services / applications.</p><p>To conclude, I hope this article encourages you to try out layered architecture in your next project.</p><p><em>Note: I work at Amazon, but the views expressed in this article are my own.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e959d75ef77" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>