<?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 Nirvana on Medium]]></title>
        <description><![CDATA[Stories by Nirvana on Medium]]></description>
        <link>https://medium.com/@nirvanatech?source=rss-63baa2e4fa64------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*p63EvQlZmVaJbrhwx96F7w.png</url>
            <title>Stories by Nirvana on Medium</title>
            <link>https://medium.com/@nirvanatech?source=rss-63baa2e4fa64------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 02:54:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nirvanatech/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[Meet the Interns Pt. 4: Victoria Atria]]></title>
            <link>https://engblog.nirvanatech.com/meet-the-interns-pt-4-victoria-atria-3673bd6caacf?source=rss-63baa2e4fa64------2</link>
            <guid isPermaLink="false">https://medium.com/p/3673bd6caacf</guid>
            <category><![CDATA[insurance-risk-assessment]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[data-integration]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[insurtech]]></category>
            <dc:creator><![CDATA[Nirvana]]></dc:creator>
            <pubDate>Mon, 06 May 2024 19:33:14 GMT</pubDate>
            <atom:updated>2024-05-06T19:33:14.677Z</atom:updated>
            <content:encoded><![CDATA[<p>Victoria is a last-year software engineering student at Pontificia Universidad Católica de Chile in Santiago, Chile. She develops backend software with Go and optimizes projects requiring heuristics. She enjoys traveling, reading novels, hiking, and playing football.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yjeKdiJy139oKAol" /></figure><h3>The Project</h3><p>Victoria was assigned to a data integration project that pulled data from the US Department of Transportation (DOT) into Nirvana.</p><p>Nirvana leverages multiple data sources to improve insurance risk assessment. One of these sources is the DOT Licensing &amp; Insurance website. The DOT website provides information on carrier authorities and previous, pending, and active insurance for fleets. Until recently, this information was cumbersome to obtain and infrequently refreshed, meaning that at Nirvana, we often could not work with the latest information. However, the DOT moved this information to a new website a few months ago.</p><p>Nirvana was looking to vet and pull the data from this new website since it’s easily accessible, frequently updated, and already unified. The plan was to establish the new website as the latest source of truth for past and current fleet insurance and reduce the data pull time to a few minutes (if not seconds). We also wanted to include new real-time features such as storing and alerting relevant fleet change events.</p><h3>The Challenges</h3><p>To the team’s delight, the new site was being updated daily, which significantly improved the information’s relevance. While this new site provided more and better data, it was evident that it was still “in the works” because of its recent launch.</p><p>Victoria had to resolve data quality challenges as much of the data had no descriptions or explanations. She had to immerse herself in the world of trucking insurance to uncover and understand the data available. The first few weeks were dedicated to deep data analysis as she vetted the new data against existing information to understand what changes were being made to the information available. She also had to write code that could be easily updated in the future as the DOT site eventually improved.</p><p>Victoria’s team decided to build a data-pulling service that ran several times daily to fetch all files of interest from the new DOT site. Processing the file caused memory issues. Additionally, as the puller runs quite frequently, one of the requirements of this project was to only store files that are different from the ones already in storage. Storage optimization required the implementation of complex deduplication logic that would not impact performance.</p><h3>The Solution</h3><p>Victoria’s team built the service to upload files to an AWS S3 bucket and store the content in a database. Initially, the service processed files in their entirety, which meant that memory usage was not optimal. As a solution, the team made the service read files in batches and leveraged S3’s multipart upload to avoid loading the entire file into memory at once.</p><p>Every time a file is fetched, a checksum algorithm is calculated based on its content and uploaded as part of the file’s metadata to avoid data duplication in storage. This allows the puller to compare the checksum with the previous file, ensuring that the puller only stores what is necessary.</p><p>While pulling these files already adds great value, Nirvana has only just scratched the surface as to how it can leverage this new source of information!</p><h3>Why Nirvana</h3><p><em>“I’ve always had a strong passion for coding as a practical solution to real-world problems. This fueled my interest to intern at a company that shared this focus, leading me to Nirvana. What stood out to me was their product-oriented approach, ensuring that my work would have a meaningful real-world impact. Its global nature also caught my attention — the prospect of collaborating with engineers worldwide was genuinely exciting. Finally, I greatly appreciated the flexibility they offered; while most backend development is in Go, I was reassured that prior experience in Go wasn’t a prerequisite. Nirvana values the learning journey, making it an ideal place for interns to enhance their skills.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hH3n4pgmAt7NsbTz" /><figcaption>From left: Nicolás, Mauricio, José, Sebastián S., Sebastián B., Victoria, and Cristóbal</figcaption></figure><h3>Life at Nirvana</h3><p><em>“From day one, I was embraced by the incredibly supportive team at Nirvana, who were always eager to guide me through any queries I had. Their collective knowledge made them valuable resources for just about anything, and I appreciated the collaborative spirit within the team. Building connections extended beyond the professional realm, and I enjoyed bonding with the entire Chile team during our after-office get-togethers. The hybrid work culture at Nirvana was a game-changer, allowing smooth collaboration with teams across different countries. My internship was a rewarding experience, serving as a platform to sharpen my software development skills and immerse myself in the vibrant startup culture that Nirvana fosters.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WvHdpj7VV3zM9QWc" /><figcaption>From left corner: Mauricio, Victoria, Nicolás, Sebastián B., José, Sebastián S., Cristóbal</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3673bd6caacf" width="1" height="1" alt=""><hr><p><a href="https://engblog.nirvanatech.com/meet-the-interns-pt-4-victoria-atria-3673bd6caacf">Meet the Interns Pt. 4: Victoria Atria</a> was originally published in <a href="https://engblog.nirvanatech.com/">Nirvana Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Meet the Interns Pt. 3: Mauricio Cari]]></title>
            <link>https://engblog.nirvanatech.com/meet-the-interns-pt-3-mauricio-cari-f4ba2d6d463a?source=rss-63baa2e4fa64------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4ba2d6d463a</guid>
            <category><![CDATA[insurtech]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Nirvana]]></dc:creator>
            <pubDate>Mon, 06 May 2024 19:10:14 GMT</pubDate>
            <atom:updated>2024-05-06T19:10:14.904Z</atom:updated>
            <content:encoded><![CDATA[<p>Mauricio is a Pontificia Universidad Católica de Chile (PUC) graduate pursuing a Master of Science (MSc) in Computer Science. He is researching automata theory and has worked with technologies like Serverless and NextJS. When he’s not working, he reads Star Wars books, participates in programming competitions, or plays board games.</p><figure><img alt="Mauricio at Nirvana’s Chile headquarters" src="https://cdn-images-1.medium.com/max/1024/0*Ct6lMFjAt_2ct6RO" /><figcaption>Mauricio at Nirvana’s Santiago, Chile headquarters</figcaption></figure><h3>The Project</h3><p>Mauricio was assigned to design and implement a new Quota Manager service for the Nirvana platform.</p><p>At Nirvana, we integrate data from multiple sources, including telematics data and motor vehicle records from different providers. Clients can leverage various external APIs we manage on a usage-based pricing model for data access. Unfortunately, so many APIs create a vulnerability around unlimited API requests. Unbounded requests to any API by the client can result in bill shock for Nirvana. As a workaround, we implemented quota managers in the client code. However, quota managers are tightly coupled with individual clients, making the solution challenging to scale.</p><p>Mauricio’s project aimed to solve some of these challenges. The Quota Manager Service he was asked to work on had four main functional goals.</p><ol><li>Any client can self-configure quota limits and a quota management strategy like a fixed window, sliding window, or leaky bucket for any API.</li><li>The service controls the API usage when multiple clients try to acquire a quota for the same API.</li><li>Administrators can assign each external API a maximum periodic cost (hourly, daily, monthly, etc.)</li><li>The service monitors metrics, raises alerts when the quota exceeds, and supports invoice verification from the external API providers.</li></ol><h3>The Challenges</h3><p>Crafting a new service required a deep dive into the world of Quota Management. Mauricio had to study various real-world examples that demonstrated varying levels of complexity. He observed that each solution was customized to its unique context and couldn’t be duplicated within Nirvana.</p><p>However, Mauricio’s research helped him identify multiple quota management strategies using the API rate limiter feature to control request rates over short intervals. Every strategy has its pros and cons. To get it right, Mauricio had to interview different Nirvana team members further to understand how their code used the different APIs.</p><p>The detailed research and numerous discussions revealed that the Quota Manager service had to be extremely flexible to control requests from any internal client to any external service. The service was also required to perform at high speed, with very low latency as it is on the critical path of every client request, and performance issues could slow down the platform experience for every client.</p><h3>The Solution</h3><p>Mauricio’s project team defined a standard data representation called <em>Resources</em> to handle this.</p><p>For example, they could define the Resources “Google Maps” or “Terminal” for external services of the same name. They created an interface that allowed clients to</p><ul><li>Create Resources and configure them with specific quota limits and refresh intervals.</li><li>Choose a quota management strategy like Fixed Window or Leaky Bucket when configuring a Resource.</li></ul><p>The team identified that a Fixed Window strategy and a quota limit of 100 per month solved many use cases. Hence, they set these as the default values within the Service. Next, the team decided to implement the Quota Manager as a gRPC server, ensuring that the service is isolated from clients and is a singleton.</p><p>Today, the Quota Manager stores client quota configurations and the chosen management strategy in PostgreSQL but loads the data into memory within the gRPC server when it starts. Frequently accessed and constantly changing values, such as the current quota available, are stored in Redis. The service thus minimizes latency by running in-memory computations instead of PostgreSQL data pulls for every request.</p><p>The Quota Manager creates and updates Resources dynamically at runtime according to the chosen strategy. If clients need to make multiple requests for an extended job run, they can acquire a different quota percentage for each request. Each successful quota acquisition returns an allocation ID the client can use to restore or <em>return</em> any unused quota from their original request. This can happen for various reasons, such as if the request they are making to the third party fails or they just did not use the complete amount of the requested quota.</p><p>Metrics such as changes in quota availability for resources and calls with their error codes are sent to DataDog to monitor each resource’s activity and detect spikes in requests. DataDog triggers alerts and allows the Nirvana team to build dashboards to better understand our quotas.</p><figure><img alt="Quota Manager architecture" src="https://cdn-images-1.medium.com/max/601/0*MjQjDoJNcGN7b588" /><figcaption>Quota Manager architecture</figcaption></figure><h3>Why Nirvana</h3><p><em>“I like coding and solving technical challenges with impact in the real world. After reading up on Nirvana’s tech stack, I knew I would get to solve problems in efficiency and concurrency — topics I am passionate about. Working with cutting-edge technology like Go, collaborating with an international team of diverse backgrounds, and a startup environment — Nirvana was a no-brainer! It was simply too great an opportunity for my personal and professional growth as a software developer; I just couldn’t turn it down.”</em></p><h3>Life at Nirvana</h3><p><em>“The onboarding process exceeded my expectations. Throughout my project journey, I had a lot of support from everyone on the team. I could ask anyone in the office any question at any time. I learned new coding practices and the reason behind many technology decisions. We also had many fun in-office events — like happy hour, after-office, and team lunches. My internship also offered a hybrid work model that allowed me to go out with friends, attend workshops, and participate in coding competitions. All in all, I highly recommend Nirvana for an enriching and valuable internship experience!”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GbkuzYce-W8MUuT4" /><figcaption>Mauricio with members of Nirvana’s Chile based Engineerig team</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4ba2d6d463a" width="1" height="1" alt=""><hr><p><a href="https://engblog.nirvanatech.com/meet-the-interns-pt-3-mauricio-cari-f4ba2d6d463a">Meet the Interns Pt. 3: Mauricio Cari</a> was originally published in <a href="https://engblog.nirvanatech.com/">Nirvana Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Investigating serialization anomalies in PostgreSQL]]></title>
            <link>https://engblog.nirvanatech.com/investigating-serialization-anomalies-in-postgresql-d9944b08edf5?source=rss-63baa2e4fa64------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9944b08edf5</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Nirvana]]></dc:creator>
            <pubDate>Fri, 26 Jan 2024 00:06:10 GMT</pubDate>
            <atom:updated>2024-01-26T01:27:40.904Z</atom:updated>
            <content:encoded><![CDATA[<p>By: <a href="https://www.linkedin.com/in/sarthakagrawal8/">Sarthak Agrawal</a></p><p>Isolation in database technologies is fundamental to ACID — Atomicity, Consistency, Isolation, and Durability. Isolation refers to the ability of a database system to keep transactions separate from each other during concurrent execution. This means that the operations of one transaction are visible to other transactions only after they are completed. The primary goal of isolation is to maintain data integrity by ensuring that concurrent transactions do not interfere with each other.</p><p>Higher isolation levels reduce the risk of data errors but often come at the cost of reduced performance due to increased locking and decreased concurrency. This article discusses the anomalies that can occur if you use PostgreSQL at the SZ isolation level. We also share our practical experiences with solving the anomalies in our high-volume tables and how we restored our system to zero serialization errors.</p><h3>What are serialization anomalies in PostgreSQL?</h3><p>For stateful services, sometimes the application semantics require SZ for correctness, and sometimes we use it just because it simplifies reasoning about correctness. For example, <a href="https://www.postgresql.org/docs/current/transaction-iso.html">PostgreSQL Docs</a> state that:</p><blockquote>“Consistent use of Serializable transactions can simplify development. The guarantee that any set of successfully committed concurrent Serializable transactions will have the same effect as if they were run one at a time means that if you can demonstrate that a single transaction, as written, will do the right thing when run by itself, you can have confidence that it will do the right thing in any mix of Serializable transactions, even without any information about what those other transactions might do, or it will not successfully commit.”</blockquote><p>However, using SZ in your database transaction means your transactions may fail due to serialization errors. Generally, this is a desirable feature for correctness. However, sometimes transactions fail even when they should not. Such false positives, or anomalies, occur when the database thinks the concurrent transactions are not serializable. However, in reality, they are serializable. <a href="https://www.postgresql.org/docs/current/transaction-iso.html">PostgreSQL Docs</a> do warn about this behavior but give no solutions.</p><blockquote>“Applications using this level (SZ isolation level) must be prepared to retry transactions due to serialization failures.”</blockquote><p>What can be the problem if serialization anomalies can be dealt with by persistently retrying them until they succeed? Well,</p><ol><li>A large number of serialization errors lead to unnecessary, and sometimes preventable, retry attempts that increase the load on the database and effective latency of queries.</li><li>In the case of highly concurrent workloads, there is no guarantee that transactions will succeed after any bounded number of retries, so there’s a risk of failure due to retry exhaustion, which is undesirable.</li></ol><p>Unfortunately, this was the exact scenario we faced in production!</p><h3>Our PostgreSQL setup</h3><p>To avoid diving into the complexities of our actual data tables, we would like to present the table structures in a simplified format. Consider the two tables shown below. The first table records resources and tracks their usage &amp; total capacity. Any resource allocations must be registered with the second table in a transaction so that both tables are consistent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*HrMSH0dBdbTxY11O3d9Vlw.png" /></figure><p>The sum of all allocations for a <em>resource_id</em> in the <em>allocations</em> table must match the value of the column used in the <em>resources</em> table.</p><p>The example may seem a bit artificial. After all, the resources table, as defined above, is simply an aggregate view of the allocations table. Having two separate tables seems superfluous. However, we share this simplified table setup to keep the article focused on the serialization solution.</p><p>Consider running the following transaction concurrently on the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WrDBscFRl9LqVszjToSTMQ.png" /></figure><p>The above transaction takes three inputs:</p><ul><li><em>resource_id</em> r,</li><li><em>allocation_id</em> i</li><li>count (to allocate x).</li></ul><p>It tries to insert the new allocation with id i into the database, but only if it does not already exist. If it exists, then it updates the existing allocation. As you can observe, an interleaving of transactions can cause the resource table and allocations table to get out of sync without serializability. So, we run all transactions in SZ.</p><h3>#Anomaly 1 — Errors double the number of requests</h3><p>In our system, we wrapped a transaction similar to the one described above in a retry block with an exponential backoff after 30 retries. We then wrote a clever stress test to verify concurrency behavior. We observed some serialization errors, but there was nothing that a few retries could not solve. Confidently, we released the query to production to experience the actual load.</p><p>We knew serialization errors were possible. After all, if <em>resource_id </em>is the same for several transactions, and they all try to update the same resource row concurrently, then some of them are sure to fail. However, we anticipated the number of failures to be too low to cause any impact. Particularly because we know that our transactions are going to be such that each transaction is guaranteed to have a unique <em>allocation_id</em> i.</p><p>On the first day in prod, we observed over 1M requests and … 1.9M serialization errors! Yes, the number of errors was nearly double the number of requests, suggesting that, on average, every request was being retried. Worse, approximately 1000 transactions failed completely after exhausting all their retry attempts (over 30!). The failed transactions were causing serious errors.</p><p>Luckily, the magnitude of errors was unexpected, but the cause was well-known.</p><h4>Our solution</h4><p>One solution to such a scenario is to acquire an explicit row-level lock on the <em>resources </em>table and run pessimistic, locking-based concurrency. It is a concurrency control method where a transaction locks the row it needs to access right at the start and holds the lock until the transaction is complete. It is “pessimistic” because it assumes the worst-case scenario where conflicts are likely.</p><p>However, in the end, we implemented a far simpler solution. We used an in-memory mutual exclusion (mutex). A mutex is a programmatic way of ensuring that only one thread can access a particular code module or data at a time. Our solution worked because our service was singleton — with only one instance throughout the application’s lifecycle. This means that all requests to the service are funneled through this single instance, making an in-memory mutex a viable solution for concurrency control. We also strengthened our in-memory stress test suite and verified no serialization failures could be detected.</p><h3>#Anomaly 2 — Failing transactions</h3><p>Once we resolved the first anomaly, we grew more confident and reduced the maximum number of retry attempts from 30 to 10. Again, we released the new version to production. Serialization failures reduced significantly BUT DID NOT STOP! We were now seeing a failure rate of &lt;2% but this was still enough to exhaust all ten retries of 100+ requests. Typically, we could have just increased the number of retries some more and called it a day, but something was unsettling about why the transactions would fail when they should not. It was clear that we did not understand something.</p><h4>Debugging the anomaly</h4><p>We started digging into the internals of SZ, and after scouring through multiple documentation pages, StackOverflow &amp; DBA SE Q/As, we discovered some previously missed details about predicate locks. Apparently, to make SZ work, Postgres has to keep track of the set of rows read by a transaction (on top of tracking the set of rows written by the transaction which it anyways does in other weaker isolation levels).</p><p>To do this, Postgres acquires what is called a <em>SIRead</em> lock on the rows it reads (or the whole table or the index page, depending upon the granularity of the read). We realized intuitively that concurrent transactions could conflict if they hold opposite read &amp; write locks on each other’s rows. Note that the <em>SIRead</em> lock is not a read lock in the traditional sense. It is not even a lock at all — the term “marker” would be more appropriate. However “SIRead lock” is the term used officially so we have used the same in this article.</p><p>Thankfully, Postgres lets you inspect all the locks it acquires through the <em>pg_locks</em> system table. As part of the debug process, we constructed two concurrent transactions in various ways to study the locks Postgres declares through <em>pg_locks</em>.After a day, we hit the jackpot. We discovered a pair of transactions that, when run in an interleaved fashion in a particular way, always resulted in a SZ failure. The interleaving looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvj_5UaghJCcUlpn_lqXZA.png" /></figure><p>This interleaving conflicts deterministically whenever one of i1 or i2 does not exist in the allocations table.</p><p>We thought this was strange and were somewhat surprised, mainly because these did not conflict when the rows existed in the table. After all, both the allocations have a different id and should be serialized in any order. Why then would Postgres fail the last one to commit, pleading a read/write dependency conflict?</p><p>To find an answer, we looked into the <em>pg_locks</em> table at each step. We observed that Postgres places an <em>SIRead</em> lock on the whole table instead of on the row, when there is no row to lock in the first place. Based on our observations, we (incorrectly) reasoned that when a row is absent, Postgres has to take a <em>SIRead</em> lock on the whole table, and once you have a lock on the whole table, the conflict is inevitable. This was a false positive, and we now know why!</p><h4>Our solution</h4><p>To fix it, we did the following.</p><ul><li>Adapted our stress test suite to highlight the interleaving scenarios more until we started seeing serialization failures again in our test suite.</li><li>Changed our transaction so that the <em>SELECT</em> is now performed outside of the transaction (in a read-only transaction)</li><li>Employed an in-memory serialization technique to still ensure that no other transaction could insert a row in-between.</li></ul><p>The reasoning was that if there’s no select statement to return empty rows, a SIRead lock on the whole table was impossible, and the problem would be solved. Our test suite was green again. With the latest change, the new serialization errors promptly disappeared, and we had a clean output again. Elated, we released it to production.</p><h3>#Anomaly 3 — Persistent failures despite query changes</h3><p>The latest change did … nothing. The rate of failures did not even budge. How could it be? A deterministically conflicting transaction on our local machines and our test suite responding positively to the fix and yet no success on real production?</p><p>After more unsuccessful debugging attempts, we finally decided to read up more on the SZ isolation level. The Postgresql docs refer to their implementation based on the Serializable Snapshot Isolation (SSI) technique. This is a technique to essentially derive serializable transaction semantics from a system that supports snapshotting (like Postgres’ MVCC). Snapshotting is just another jargon for Repeatable Read (RR).</p><h4>Limitations in PostgreSQL implementation</h4><p>The <a href="https://arxiv.org/pdf/1208.4179.pdf">linked paper</a> goes into all the details, and is a surprisingly friendly read. For the sake of this discussion, we distill the essence of the paper. Finding serialization anomalies means finding a cycle in a graph that maps read/write dependencies among concurrent transactions. However, finding the cycle is a complex, resource-intensive task, so with some cleverness, the paper demonstrates a necessary (but not sufficient) condition for a cycle to occur. Because the condition is only necessary, and not sufficient, any implementation relying on it is bound to give false positives as it may think that a cycle exists when it does not. False positives do not influence correctness, only performance, and in conjunction with multiple additional false-positive mitigation optimizations that Postgres employs (described in the paper), the implementers found the trade-off too good to give away.</p><p>So what we faced was not a false positive (well, it was, but not due to what we thought as <strong>anomaly 2</strong>). Instead, it was an artifact of how predicate locks are implemented. It turns out Postgres does not take predicate locks on the result set of a query, but on all the rows it has to scan to reach the query row.</p><h4>Reason behind re-occuring failures</h4><p>In particular, if the query planner can choose one of the two to discover your result set</p><ol><li>SeqScan. If used, the <em>SIRead</em> lock ends up locking the whole table — even if you can prove via a unique constraint that there could have been at most one row in the result set.</li><li>Index scan. If the row is not found during an index scan, Postgres locks the index page on which the row would <em>have been.</em></li></ol><p>Now, the query optimizer is its own beast. It chooses to do a SeqScan for a primary key if it thinks that will be faster. And unknown to us, that was happening in our<em> local</em> systems. The allocations table in our local systems was so small that an ordinary select statement would consistently regress to a SeqScan instead of a Unique Index lookup under certain circumstances. This caused too wide <em>SIRead</em> locks and high SZ failures which we observed previously. This is also why our previous fix worked on local, but did not work on production. In production, the table has 10M+ rows, and no sane query planner would choose a SeqScan. Always an index scan, so always row-level or page-level locks, which have a much lower probability of conflict.</p><p>However, the higher failure percentage was due to the SeqScan on the resources table. Yes, even in production, the resources table was small (about ten rows), and it was meant to be small. Query planner seems to randomly flip-flop between choosing a SeqScan vs. Pkey-scan on the smaller table (still unknown to us why). We reasoned that whenever it chooses a SeqScan we see an SZ failure.</p><p>We verified our hypothesis by temporarily stuffing the resources table in production with many fluff rows to force the planner to choose index lookup over SeqScan. The SZ failure rate dropped overnight to a staggering 0.001% (still not 0!) largely confirming our hypothesis.</p><h4>Final solution</h4><p>But our reading of the paper also suggested a better solution. We now understand that the only difference between RR and SZ comes from using <em>SIReadLocks</em> (to track rw-anti dependencies in paper-speak) to detect <em>potential</em> cycles. A surprising revelation from the paper was that a <strong>read-only RR can never fail because it holds no locks to conflict, but a read-only SZ can fail due to <em>genuine</em> anomalies.</strong> The absence of <em>SIRead</em> locks makes RR weaker and prone to SZ anomalies. However, if the transaction is designed in such a way so that all rows that are read are also written to (or updated), then RR is no weaker than SZ because it misses no locks (indeed even SZ promotes <em>SIRead</em> Lock to a full Exclusive Lock upon a write to the same row, so no <em>SIRead</em> Locks linger past the <em>COMMIT</em> of such SZ transactions).</p><p>Our transactions are implicitly of such a nature, as we update the same row in the allocations &amp; resources table, which we attempt to read (even if unsuccessful). Thus, <strong>we could safely downgrade to RR</strong> <strong>without compromising on any SZ guarantees</strong> and enjoy the simplicity of MVCC. Since our change, we have not seen a single SZ failure in our system.</p><h3>Conclusion</h3><p>This was our journey from 1.9M failures to zero. Some final observations.</p><ol><li>Choosing SZ by default for your transactions simplifies reasoning at the application level, but under high volumes, serialization failures can become a real nuisance, not simply solvable through “more” retries. The trade-off is essential.</li><li>We made the mistake of assuming failures reproducible locally were the same as those happening in production. As we later realized, query planners may choose drastically different plans and system configurations could also be so different, making reproducing failures a challenge.</li><li>When using SZ, remember that predicate locks are acquired on all the rows scanned rather than just the result set. Queries that scan large portions of the table or too small tables are not good candidates for this isolation level as they lead to higher number of conflicts.</li><li>Read-only SZ transactions may also fail due to real serialization anomalies (not just false positives). In our application, we discovered at a few places we were starting a read-only SZ transaction reading rows from multiple tables but then aborting the transaction if the read values were not meaningful. The reads can not be considered serialized until the transaction commits successfully.</li></ol><p>Ultimately, reducing serialization errors may require query redesign so you can use PostgreSQL in Repeatable Read mode — like we did!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9944b08edf5" width="1" height="1" alt=""><hr><p><a href="https://engblog.nirvanatech.com/investigating-serialization-anomalies-in-postgresql-d9944b08edf5">Investigating serialization anomalies in PostgreSQL</a> was originally published in <a href="https://engblog.nirvanatech.com/">Nirvana Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we made PostgreSQL work in unit tests]]></title>
            <link>https://engblog.nirvanatech.com/how-to-run-unit-tests-on-production-data-using-golang-postgresql-f2ebf38a3271?source=rss-63baa2e4fa64------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2ebf38a3271</guid>
            <dc:creator><![CDATA[Nirvana]]></dc:creator>
            <pubDate>Tue, 17 Oct 2023 01:09:51 GMT</pubDate>
            <atom:updated>2023-10-19T21:00:51.556Z</atom:updated>
            <content:encoded><![CDATA[<p>By: <a href="https://www.linkedin.com/in/hogangreg/">Greg Hogan</a></p><p>At <a href="https://www.nirvanatech.com/">Nirvana Insurance,</a> we strive to make unit testing as frictionless and comprehensive as possible. Our commitment to quality and efficiency led us to experiment with various unit testing approaches, especially in data-handling operations. We wanted to test exactly what runs in production, meaning that we really wanted to test our data wrappers and object-relational mapping (ORM) against the same <a href="https://www.postgresql.org/">PostgreSQL database</a> we run in production.</p><p>Eventually, we discovered that PostgreSQL is extremely fast at cloning template databases, and we could use this fact to simply clone a fully migrated template database (DB) for every unit test.</p><p>In this article, we share our unit testing journey, challenges, and the solution that worked for us. We also include some PostgreSQL tips and tricks for those interested in adapting our ideas for your use case.</p><h3>Unit testing goals and challenges</h3><p>When we started, our developers were writing in-memory mock implementations of our data wrappers in the unit tests and avoiding our database ORM entirely. However, this approach had many issues:</p><ul><li>It was not testing our production code paths.</li><li>Mock wrappers did not enforce database schema or constraints.</li><li>Very high overhead for developers to write mock implementations of the DB.</li></ul><p>Dissatisfied with the overall efficiency and quality of testing, we decided to brainstorm on everything we were looking for in our unit test persistence layer. Our initial requirements list was as follows.</p><ol><li>Tests must remain <strong>fast</strong> and must be able to <strong>run</strong> <strong>concurrently.</strong></li><li>Tests should hit a <strong>live PostgreSQL database</strong>, the same version we run in production.</li><li>The database <strong>schema</strong> should always be <a href="https://github.com/golang-migrate/migrate"><strong>fully migrated</strong></a> to the exact <strong>version of the branch being tested.</strong></li><li>All tests should <strong>run in isolation</strong> from one another with no side effects — continuous integration (CI) should be able to concurrently test multiple branches with different or conflicting table schemas.</li></ol><h3>Approaches we considered but did not use</h3><p>We tried a few different solutions before finding the one that worked for us.</p><h4>Attempt #1: Mocking out the database code</h4><p>As mentioned above, initially, we tried using <a href="https://github.com/DATA-DOG/go-sqlmock">SQL mock driver for Golang</a> to simulate any SQL driver behavior in tests without needing an actual database connection. Unfortunately, that solution:</p><ul><li>Does not enforce database schema or constraints</li><li>Does not test our database ORM</li><li>Does not support PostgreSQL extensions like PostGIS</li><li>Has high developer effort to write unit tests</li></ul><h4>Attempt #2: Using go-txdb</h4><p>Next, we attempted to use <a href="http://github.com/DATA-DOG/go-txdb">go-txdb</a> to start an isolated PostgreSQL transaction for every unit test, and have our code execute inner transactions within that outer transaction. This theoretically would allow each unit test to read and write data to the database but operate in complete isolation from other unit tests. Unfortunately, again, we faced the following challenges.</p><ul><li>Encountered several blocking issues related to savepoints and transaction errors.</li><li>Performance suffered because the database had to maintain each long-running transaction.</li></ul><h4>Attempt #3: Using testcontainers-go</h4><p><a href="https://github.com/testcontainers/testcontainers-go">Testcontainers-go</a> is a popular project that streamlines the process of spinning up transient test containers. For instance, it is super easy to start a new PostgreSQL container and then wait for a log message like “ready to accept connections” before issuing queries against the database. We attempted to use it for spinning up a separate container per unit test.</p><p>The main drawback to this approach was performance:</p><ul><li>We ended up with a huge number of PostgreSQL containers running (one per test), and they were all competing for limited system resources.</li></ul><p>The <em>testcontainers</em> team has a hosted backend where we could spin up many containers to throw more hardware at the problem, but this seemed both wasteful and expensive.</p><h3>Template databases to the rescue 🎉</h3><p>After trial and error, our test engineers zeroed in on an incredibly useful feature of PostgreSQL called <a href="https://www.postgresql.org/docs/current/manage-ag-templatedbs.html">template databases</a>.</p><h4>The theory behind the solution</h4><p>Whenever you create a new database in PostgreSQL, you are actually <strong>cloning</strong> it from an already present template database. Copying templates is how PostgreSQL makes <em>every</em> new database, including the default postgres<br><strong> </strong>one. If we spin up a brand new PostgreSQL container, we can see that three databases were created automatically:</p><pre>postgres=&gt; select datname, datistemplate, datallowconn from pg_database;<br>      datname       | datistemplate | datallowconn <br>--------------------+---------------+--------------<br> template1          | t             | t<br> template0          | t             | f<br> postgres           | f             | t</pre><p>The two databases — template1 and template0 — are standard system databases that exist in every newly created database cluster. From the<a href="https://www.postgresql.org/docs/current/manage-ag-templatedbs.html"> PostgreSQL documentation</a> on template databases, we see that postgres is simply a copy of the template1 database, and <em>template1</em> is a copy of <em>template0</em>.</p><figure><img alt="(Source: PostgreSQL)" src="https://cdn-images-1.medium.com/max/1024/0*KuKkogdv8leQ98AN" /><figcaption>(Source: <a href="https://www.postgresql.org/docs/current/manage-ag-templatedbs.html">PostgreSQL</a>)</figcaption></figure><p>You can modify this <em>template1</em> database in any way: add a table, insert some data, create new extensions, or install procedural languages. Any of these actions would be propagated by default to subsequently created databases. Furthermore, PostgreSQL makes it easy to create many template databases, and select which one to clone when creating a new database.</p><h4>Our solution</h4><p>In order to efficiently utilize system resources, we start a single <a href="https://github.com/bitnami/containers/blob/main/bitnami/postgresql/README.md">PostgreSQL container</a> in Docker. We then create a new <em>nirvana_template</em> database, and fully migrate it to the latest schema for the branch.</p><p>Each test then instantiates a new copy of this fully migrated template database, and then drops the test database after the test completes.</p><pre>CREATE DATABASE test_foo WITH TEMPLATE nirvana_template OWNER tester;<br>--<br>-- &lt;&lt; Execute the unit test using test_foo &gt;&gt;<br>--<br>DROP DATABASE IF EXISTS test_foo WITH (FORCE); </pre><p>In production, Nirvana has two separate PostgreSQL RDS instances named <strong>nirvana</strong> and <strong>fmcsa</strong>. In tests, however, we simply create two separate template databases that reside in the same PostgreSQL container. The following is what our <em>pg_database</em> list looks like during unit testing:</p><pre>postgres=&gt; select datname, datistemplate, datallowconn from pg_database;<br>           datname           | datistemplate | datallowconn <br>-----------------------------+---------------+--------------<br> template1                   | t             | t<br> template0                   | t             | f<br> postgres                    | f             | t<br> nirvana_template            | t             | f<br> fmcsa_template              | t             | f<br> nirvana_template_oxw5vcaqw3 | f             | t<br> nirvana_template_y60sw8n6ay | f             | t<br> nirvana_template_5ycmgmpt69 | f             | t<br> fmcsa_template_46br5n4zt6   | f             | t<br> nirvana_template_s9gtyoh4v7 | f             | t<br> fmcsa_template_rpzhjgklaz   | f             | t<br> nirvana_template_4xqm3um2lr | f             | t<br> nirvana_template_us845inuo9 | f             | t<br> fmcsa_template_4nlmcek5r6   | f             | t</pre><h3>How everything works</h3><p>Steps to implement PostgreSQL template databases for unit testing are given below.</p><h4>1. Create a fully migrated template database that is ready to be cloned</h4><p>This template database should be fully migrated to the latest DB schema for the branch being tested. This may include experimental or dangerous schema modifications; if you make a mistake, simply blow away the container and start over.</p><p>See the diagram below.</p><figure><img alt="Steps to create a template database" src="https://cdn-images-1.medium.com/max/1024/0*B25n3rdyFbQ-924b" /><figcaption>Steps to create a template database</figcaption></figure><h4>2. For each unit test, clone a new transient database from the template</h4><p>Each unit test spins up its isolated database within the PostgreSQL container. This database is a complete copy of the template <em>nirvana_template</em> and may be freely modified and queried. The test may drop tables, insert data, query rows, and execute transactions completely isolated from all other concurrently running tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*02HJhT2XGiH1tMXk" /><figcaption>Creating a unit test database instance from our template</figcaption></figure><h3>Benchmarks</h3><p>The latency for cloning a new database from template is proportional to the size of the template schema. This size can be found using:</p><pre>SELECT pg_size_pretty( pg_database_size(&#39;nirvana_template&#39;))</pre><p>Our nirvana_template database is roughly ~14MB in size, and creating a new database from this template takes <strong>~40ms</strong> per test.</p><p>This latency can be amortized to some degree by running tests concurrently, but it is reasonable to expect a minor performance hit compared with in-memory mocks. However, we’ve found that the many benefits of executing tests directly against PostgreSQL far outweigh the costs.</p><h3>Additional Tips and Tricks</h3><h4>Max connections limit</h4><p>If you have many unit tests running concurrently, and each unit test has several connections open to several databases, it is possible to exceed the default max_connections limit of 100. There are two approaches to solving this problem, which will largely depend on your environment and circumstances:</p><ul><li>Increasing the <em>postgresql.conf</em> <strong>max_connections</strong> property (along with <strong>shared_buffers</strong> and <strong>max_wal_size</strong>).</li><li>Use a connection pool such as<a href="https://www.pgbouncer.org/config.html"> PgBouncer</a> or<a href="https://www.pgpool.net/mediawiki/index.php/Main_Page"> Pgpool</a>.</li></ul><p>We spin up a GitHub PostgreSQL<a href="https://docs.github.com/en/actions/using-containerized-services/creating-postgresql-service-containers"> service container</a> in our CI workflow for unit testing, and have each unit test create copies of the template databases as needed. View more tips for optimizing the DB for a large number of concurrent connections <a href="https://stackoverflow.com/questions/9407442/optimise-postgresql-for-fast-testing">here</a>.</p><h4>“Source database is being accessed by other users”</h4><p>Before PostgreSQL can clone a template database, it needs to ensure that there are no other potential writers in the DB. It does this by taking a conservative approach and ensuring that there are no active connections to the template DB. If you attempt to clone a database that has active connections (even if those connections are just other <em>CREATE DB WITH TEMPLATE</em> calls), you will receive the error:</p><blockquote><strong>source database “nirvana_template” is being accessed by other users</strong></blockquote><p>This means that we either need to ensure that there are no connections to the DB at all, or we need to set <strong>datistemplate=‘true’</strong> and <strong>datallowconn=‘false’</strong> for the database.</p><p>If you need to drop the template database, remember to first set datistemplate=false; otherwise the template database is read-only.</p><h4>Simplifying database provisioning with dependency injection</h4><p>What makes this whole process even easier is that we use an application framework called<a href="https://github.com/uber-go/fx"> fx</a> to inject all of our dependencies, so tests themselves do not need to know anything about template databases or PostgreSQL containers. Instead, tests ask for dependencies to be provided, and our <strong>fxtest</strong> infrastructure automatically provides an appropriate <strong>*sql.DB</strong> connection to the appropriate database instance.</p><h3>Conclusion</h3><p>We had fun experimenting with different solutions until we could implement exactly what we wanted. Our unit tests now transparently read and write to fully isolated PostgreSQL databases, without being aware of template databases or testcontainers running behind the scenes. Keep an eye out for a future blog post on how we built out our dependency injection and testing infrastructure around fx.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2ebf38a3271" width="1" height="1" alt=""><hr><p><a href="https://engblog.nirvanatech.com/how-to-run-unit-tests-on-production-data-using-golang-postgresql-f2ebf38a3271">How we made PostgreSQL work in unit tests</a> was originally published in <a href="https://engblog.nirvanatech.com/">Nirvana Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Meet the Interns Pt. 2: Kushagra Gupta]]></title>
            <link>https://engblog.nirvanatech.com/meet-the-interns-pt-2-kushagra-gupta-198cb880f9e7?source=rss-63baa2e4fa64------2</link>
            <guid isPermaLink="false">https://medium.com/p/198cb880f9e7</guid>
            <category><![CDATA[internships]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[testing-framework]]></category>
            <category><![CDATA[pricing-model]]></category>
            <dc:creator><![CDATA[Nirvana]]></dc:creator>
            <pubDate>Wed, 27 Sep 2023 19:51:43 GMT</pubDate>
            <atom:updated>2023-09-27T20:04:01.069Z</atom:updated>
            <content:encoded><![CDATA[<p>This summer, Nirvana Insurance hosted a group of four software engineering interns in our Bangalore office, where they had the opportunity to contribute to our core product offering. As their internships come to an end, we’ll be spotlighting each of the interns and their projects over the next few weeks.</p><figure><img alt="From left: Avi Kothari, Abhinav Sharma, Manthan Dalmia, Kushagra Gupta" src="https://cdn-images-1.medium.com/max/1024/0*l4I5kyDd259T3BGu" /><figcaption><em>From left: Avi Kothari, Abhinav Sharma, Manthan Dalmia, Kushagra Gupta</em></figcaption></figure><h3>Kushagra Gupta</h3><p><a href="https://www.linkedin.com/in/kushagra-gupta-8907561bb/">Kushagra </a>is a senior at the Indian Institute of Technology, Delhi (IITD), pursuing a Bachelors of Technology (B.Tech) in Mathematics &amp; Computing. Previously, he’s worked on machine learning (ML), and data science projects. Currently, he’s focusing on mastering backend development and exploring the intricacies of graph algorithms. When he’s not coding for school or work, he’s coding competitively &amp; for fun, traveling, and practicing his photography skills.</p><figure><img alt="Kushagra Gupta, Nirvana intern — IIT Delhi ‘24" src="https://cdn-images-1.medium.com/max/1024/0*j20Z_469vzDeoAJc" /><figcaption><em>Kushagra Gupta, Nirvana intern — IIT Delhi ‘24</em></figcaption></figure><h3>The Project</h3><p>Nirvana’s pricing models consist of a core pricing engine written in our in-house domain-specific language (DSL) known as RateML. These models are versioned based on factors like geographies and periodic updates. Because of this, Nirvana is required to rerun the same model for more than a year for each customer, imposing backward compatibility requirements on the system. This requires the engineering team to oversee multiple models and accompanying model glue code.</p><p>Enter Kushagra, embarking on his internship here at Nirvana, ready to dive in and learn something new. His mission? To create a novel testing framework for the complex pricing engine dependencies we’ve outlined above. His primary objective was to implement continuous integration (CI) tests for pricing engines, designed to detect regressions in the pricing pipeline for all of Nirvana’s pricing models. While the initial focus was on validating the pricing model’s output, as the project evolved, Kushagra and his team expanded their objectives to include crafting assertions that could uncover potential bugs within the rating model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/0*TAW13Eqte2gWDrdw" /></figure><h3>The Challenges</h3><p>While parallelizing pricing engine tests, the team confronted a race issue. Tests, although correct, unexpectedly timed out specifically when executed in parallel. Kushagra set out to tackle this conundrum by integrating internally developed components, which came with a dose of legacy code. This legacy code required extensive analysis before integration.</p><p>In addition to legacy code analysis, Kushagra also dove into the intricacies of managing race conditions in concurrent operations and ensured that the data insertion into the database adhered to the principles of atomicity, isolation, &amp; durability (ACID).</p><p>Despite all of these challenges, the core challenge with testing the pricing engine was its dependence on multiple data sources, leading to inefficient database and API calls. The next section reveals how Kushagra designed the testing framework while navigating these challenges.</p><h3>The Solution</h3><p>To ensure the required efficiency of his design, Kushagra collaborated with the engineers behind the original RateML pricing framework, tapping into their expertise to craft an optimal solution. Their goal was to write O(n) tests while still achieving reasonable coverage on models that scaled quadratically.</p><p>Kushagra and the team first identified which parts of the pricing codebase underwent frequent changes. Concurrently, he researched strategies for implementing parametric tests capable of validating changes across multiple models simultaneously.</p><p>Initially, Kushagra’s tests were time-intensive, averaging more than 120 seconds per variation. To address this, he implemented extensive fixtures and <a href="https://stackoverflow.com/questions/346372/whats-the-difference-between-faking-mocking-and-stubbing">fakes</a>. He and the team also parallelized the tests to concurrently handle the 300-and-growing number of variations.</p><figure><img alt="Source: Software Testing Magazine" src="https://cdn-images-1.medium.com/max/863/0*y_vAjjlIST9TwlxV" /><figcaption><em>Source: </em><a href="https://www.softwaretestingmagazine.com/knowledge/unit-testing-fakes-mocks-and-stubs/"><em>Software Testing Magazine</em></a></figcaption></figure><p>As he was building out the solution to this problem, he leaned heavily on his Nirvana mentor, <a href="https://www.linkedin.com/in/ayush-sharma-263705148">Ayush Sharma</a>. Ayush guided Kushagra with patience as they engaged in various code debugging sessions and collaborative research.</p><p>After completing his initial project, he had the opportunity to work on product enhancements in the auth components, namely the forgot password flow and supporting bulk user insertion. On these new projects, <a href="https://www.linkedin.com/in/vedant-mamgain/">Vedant Mamgain</a> became his mentor, further enhancing his understanding of coding practices at Nirvana. His guidance focused on code writing, coding best practices, and optimizing functionality.</p><figure><img alt="Pictured: VP of Engineering, Deepak Angrula and various engineers including Kushagra chat at our Nirvana Bangalore office" src="https://cdn-images-1.medium.com/max/1024/0*3M22Ui0JrSRj7-2V" /><figcaption><em>VP of Engineering, Deepak Angrula and various engineers including Kushagra chat at our Nirvana Bangalore office</em></figcaption></figure><h3>Why Nirvana</h3><p><em>“My introduction to Nirvana came through our college’s placement cell, and I also sought insights from seniors and my LinkedIn connections. It became evident that Nirvana held a distinct position among early-stage startups. The founders’ unique backgrounds piqued my interest. As someone passionate about computer science, I derive satisfaction from writing code that has real-world impact, contributes to product development, and yields visible outcomes. To me, Nirvana seems like the perfect platform to refine skills and immerse myself in the dynamic startup culture. The diverse backgrounds of Nirvana’s employees also attracted me, promising ample exposure during my time there.</em></p><p><em>This held true as I worked extensively on the product side of projects, such as refining the user flow for forgotten passwords and streamlining the process for creating bulk users.”</em></p><h3>Life at Nirvana</h3><p><em>“Starting at Nirvana was an incredibly smooth process, thanks to the strong support from the entire team. Ayush, my mentor, played a significant role during my time there. He patiently addressed all my queries and guided me through various problem-solving discussions. Engaging in code debugging sessions and collaborative research was a part of our enjoyable interactions. In subsequent projects, Vedant became my mentor, further enhancing my understanding of coding practices at Nirvana. His guidance focused on code writing, best practices, and optimizing functionality.</em></p><p><em>My overall interaction with the team was positive and enriching. Besides work-related conversations, we often organized outings and engaging events in Bangalore. Our connection extended to lunchtime gatherings, where we enthusiastically discussed common interests, favorite shows, and movies.”</em></p><figure><img alt="Nirvana Bangalore office team building event" src="https://cdn-images-1.medium.com/max/1024/0*brcOND0vgRCB3HQ6" /><figcaption><em>Nirvana Bangalore office team building event</em></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=198cb880f9e7" width="1" height="1" alt=""><hr><p><a href="https://engblog.nirvanatech.com/meet-the-interns-pt-2-kushagra-gupta-198cb880f9e7">Meet the Interns Pt. 2: Kushagra Gupta</a> was originally published in <a href="https://engblog.nirvanatech.com/">Nirvana Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Meet the Interns: Abhinav Sharma]]></title>
            <link>https://engblog.nirvanatech.com/meet-the-interns-abhinav-sharma-2a8cdfffcd8b?source=rss-63baa2e4fa64------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a8cdfffcd8b</guid>
            <category><![CDATA[internships]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[insurance]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Nirvana]]></dc:creator>
            <pubDate>Tue, 12 Sep 2023 15:37:53 GMT</pubDate>
            <atom:updated>2023-09-12T21:36:02.729Z</atom:updated>
            <content:encoded><![CDATA[<p>This summer, Nirvana Insurance hosted a group of four software engineering interns in our Bangalore office, where they had the opportunity to contribute to our core product offering. As their internships come to an end, we’ll be spotlighting each of them and their contributions.</p><figure><img alt="From left: Avi Kothari, Abhinav Sharma, Manthan Dalmia, Kushagra Gupta" src="https://cdn-images-1.medium.com/max/880/0*Rvl7A7IvAurnv7nd" /><figcaption><em>From left: Avi Kothari, Abhinav Sharma, Manthan Dalmia, Kushagra Gupta</em></figcaption></figure><h3>Abhinav Sharma</h3><p><a href="https://www.linkedin.com/in/abhinav-sharma-920a76202/"><strong>Abhinav</strong></a> is a senior at the Indian Institute of Technology, Delhi (IITD), pursuing a Bachelors of Technology (B.Tech) in Mathematics &amp; Computing. Previously, he’s worked on blockchain development, machine learning (ML), deep learning (DL), and natural language processing (NLP). Currently, he’s trying his hand at backend development in Go! When he’s not coding, he’s either gaming or gyming.</p><figure><img alt="Abhinav Sharma, Nirvana intern — IIT Delhi ‘24" src="https://cdn-images-1.medium.com/max/646/0*oh0oZrZgrxmCRrN8" /><figcaption><em>Abhinav Sharma, Nirvana intern — IIT Delhi ‘24</em></figcaption></figure><h3>The Project</h3><p>Nirvana follows a monorepo approach and has a large repository to which everyone across the engineering organization contributes. A trunk-based development model resulted in high merge velocity on main and was causing friction. Developers had to babysit their pull requests (PRs) since another merge could invalidate their merge attempt. Resubmission attempts were also getting invalidated. Nirvana initially solved this problem by leveraging the new GitHub Merge Queue (GMQ) feature, but there were still issues around both speed-to-merge as well as cost efficiency when it came to running comprehensive continuous integration/continuous deployment (CI/CD) checks.</p><p>Abhinav was assigned the Nirvana Merge Queue (NMQ) project to build an in-house merge queue (MQ) solution and replace the GMQ altogether. The NMQ enhances the user experience as compared to the GMQ, along with a better overall observability using Datadog. It was to be developed in such a way that it matched/exceeded the capabilities of the GMQ. The main features of NMQ include:</p><ul><li>Speculative checks</li><li>Instant merge on up-to-date PRs</li><li>Notifications to users</li><li>Crash recovery support</li></ul><h3>The Challenges</h3><p>In the beginning of the internship, everything was new and Abhinav was not very familiar with Git and GitHub, let alone building an MQ. He also faced challenges while deriving the MQ algorithm as he aimed to facilitate speculative checks.</p><p>The initial phase of his internship was spent on mastering Git and GitHub utilities such as: webhooks, application programming interfaces (APIs), actions, and Amazon Web Services (AWS, i.e.: Lambda, Simple Queue Service (SQS), Elastic Container (ECS)), etc. It was a huge learning curve for Abhinav in a very short period of time.</p><h3>The Solution</h3><p>As Abhinav and his team designed the project, they thought about three properties they were looking to achieve:</p><ul><li><strong>Reliability </strong>— merge PRs that pass checks individually</li><li><strong>Cost-effectiveness </strong>— minimum CI checks</li><li><strong>Velocity — </strong>maximize throughput and minimize latency</li></ul><p>Due to practical constraints, the team could only prioritize two of these properties. They decided to focus more on <strong>reliability &amp; velocity</strong> (while keeping cost-effectiveness in mind).</p><figure><img alt="Workflow explaining how NirvanaMQ merges Pull Requests by leveraging GitHub Webhooks, Github API, and various AWS services" src="https://cdn-images-1.medium.com/max/1024/0*yUicPZm4KZyZOd-Q" /><figcaption><em>Workflow explaining how NirvanaMQ merges Pull Requests by leveraging GitHub Webhooks, Github API, and various AWS services</em></figcaption></figure><p>Abhinav and his team decided to run additional checks on a PR simultaneously, assuming the requests in front had merged. If the checks passed successfully, they merged requests directly without running another round of checks. Essentially, they changed the design so that PRs completed CI checks in parallel for faster merges. The team decided not to use databases to keep the architecture stateless and easy to maintain. Instead, they relied on storing information against GitHub PRs in the form of labels to provide strong crash recovery guarantees.</p><p>The end product was a much improved version and Abhinav was excited to have contributed and solved a real-world challenge that developers at Nirvana were experiencing. Due to Abhinav’s efforts, the NMQ is up and running and being used regularly by the whole company!</p><p>He’s now working on further enhancing the user experience, along with a UI dashboard creation, and monitoring metrics for NMQ using DataDog.</p><figure><img alt="Comparison table highlighting impact of NMQ intern project" src="https://cdn-images-1.medium.com/max/1024/0*ao6BKLURNDwjB9xa" /><figcaption><em>Comparison table highlighting impact of NMQ intern project</em></figcaption></figure><h3>Why Nirvana</h3><p><em>“I am a tech enthusiast and enjoy spending time writing code and building software. As an intern aspirant, I was determined to join a company where I could learn new skills and get my hands dirty on cutting-edge tech. Backed by a strong tech leadership &amp; the latest tech stack, Nirvana provided an opportunity for professional growth along with work-life balance and competitive compensation. I am glad I applied to Nirvana and they selected me!”</em></p><h3>Life at Nirvana</h3><p><em>“The transition into the team was a very smooth experience. There was already a lot of documentation present to quickly ramp up and understand Nirvana’s tech stack and the product. The team I was working with was fully remote, so we had regular online meetings and huddles, where we brainstormed ideas related to the project, and had some really fruitful discussions. Also, I had a great experience with other teams working from the office. We had several parties, and some unofficial catch ups too. I even went for an indoor cricket match with all the other interns and employees. I felt very lucky to experience the vibrant culture at Nirvana first-hand!”</em></p><figure><img alt="Nirvana Bangalore office team building event" src="https://cdn-images-1.medium.com/max/1024/0*eocHAjN8Xr2UJZed" /><figcaption><em>Nirvana Bangalore office team building event</em></figcaption></figure><p>During his time at Nirvana, Abhinav benefited from the mentorship of <a href="https://www.linkedin.com/in/sarthakagrawal8/"><strong>Sarthak Agrawal</strong></a>, an alum of IITD and an engineer who previously completed the Nirvana internship before joining the staff in 2022. Sarthak has strong technical skills, and knows the Nirvana techstack inside out. Sarthak’s technical expertise paved the path for long discussions and debugging sessions while the two worked on the NMQ project together. Ultimately, Abhinav was able to thrive and succeed in his internship due to the valuable coaching he received from his mentor and other members of the Nirvana India developers team, as well his own hard work, curiosity, and commitment to excellence.</p><p>Thank you for your hard work this summer, Abhinav and we can’t wait to have you on the team after graduation!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a8cdfffcd8b" width="1" height="1" alt=""><hr><p><a href="https://engblog.nirvanatech.com/meet-the-interns-abhinav-sharma-2a8cdfffcd8b">Meet the Interns: Abhinav Sharma</a> was originally published in <a href="https://engblog.nirvanatech.com/">Nirvana Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Orchestrating data science workflows at scale]]></title>
            <link>https://engblog.nirvanatech.com/orchestrating-data-science-workflows-at-scale-1e630c99bae?source=rss-63baa2e4fa64------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e630c99bae</guid>
            <category><![CDATA[telematics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Nirvana]]></dc:creator>
            <pubDate>Tue, 18 Jul 2023 13:16:35 GMT</pubDate>
            <atom:updated>2023-07-28T20:49:13.451Z</atom:updated>
            <content:encoded><![CDATA[<p>By: <a href="https://www.linkedin.com/in/sarthakagrawal8/">Sarthak Agrawal</a></p><p>Accurate underwriting requires precise estimation and modeling of the insured’s risk. Traditionally, human experts achieve accuracy by analyzing data like vehicle reports and fleet stats. While most insurance companies use a handful of data points, Nirvana improves underwriting by leveraging IoT or intelligent sensor data. Specifically, we use telematics data like driver behavior, vehicle location, vehicle activity, and engine diagnostics, which we continuously receive and process from IoT devices attached to the insured vehicles. Analytics of this data gives us previously unexplored insights into the risk and behavior of our client’s fleets. One of our goals is to estimate risk as quickly as possible to minimize the turnaround time we take from the moment we receive an application to generating a quote.</p><p>The challenge, of course, lies in processing very large data volumes with efficiency and accuracy. Traditional MLOps practices have a handful of models, trained once and then used across all customers. At Nirvana, we take the unique approach of running our ML workflows on a per-customer basis. We train and deploy a new model on each customer’s data for the best fit. We then use the per-customer model to generate insights such as vehicle-level and driver-level risk profiles to segment the risk. Once trained, our models output insights continuously per week or month to generate trends.</p><p>However, training models per customer create unique challenges for our engineering team. For example, we have to think about how to:</p><ul><li>Run some data pipeline steps concurrently and manage data flow between different steps.</li><li>Version both the pipelines themselves and the artifacts produced by them.</li><li>Automate the entire MLOps stack while managing monitoring and configuration drift challenges.</li></ul><p>This article dives deeper into how we solve the first challenge of MLOps — writing data pipelines that scale and infrastructure to scale them.</p><h3>Adopting the dataflow paradigm</h3><p>We adopted the dataflow paradigm that breaks down a data pipeline into logical steps and expresses data or control dependencies among them as a graph. The various steps and data dependencies create a directed acyclic graph(DAG). An orchestrator executes the graph, optimizing run time by automatically deducing which steps can run in parallel.</p><p>Running all the steps in a single machine may be suitable for local or development testing but unsuitable for large-scale production. Consider the problem of running ten steps in parallel, each of which requires a (4vCPU, 32GB) machine. Therefore, an orchestrator is associated with a compute cluster of several machines capable of running the steps.</p><p>So, to run the steps, the orchestrator places them into one of the available machines in the compute cluster. However, even for a single pipeline, our workloads are not uniform and can have frequent peaks of high resource requirements. Therefore, we require the ability to provision and deprovision compute responsively according to pipeline requirements.</p><figure><img alt="An illustration showing a DAG of data dependencies among the steps in one of our actual production pipelines. Step names have been anonymised for illustration." src="https://cdn-images-1.medium.com/max/1024/1*rWrkZZqbjjVbI_XOLP-ZEg.png" /><figcaption>An illustration showing a DAG of data dependencies among the steps in one of our actual production pipelines. Step names have been anonymised for illustration.</figcaption></figure><h3>What we were looking for in our solution</h3><p>Our criteria while researching potential solutions were as follows.</p><h4>Application framework</h4><p>We required an application framework / SDK for data scientists to author their workflows and pipelines. We wanted the framework to be simple and infra-agnostic. Here simple means concerning usage and not expressiveness. Various control flow constructs such as branching, dynamic fan-out, and conditionals are desirable. We wanted a framework that could provide a self-serve and holistic experience for our data scientists, leading to faster development iterations.</p><h4>Orchestrator</h4><p>The framework would output a DAG, which a production-grade orchestrator must then interpret and run. All software and hardware can crash. But faults in the orchestrator are considered critical. Therefore we needed a highly-available orchestrator.</p><h4>On-demand infrastructure</h4><p>Finally, the orchestrator needs a compute cluster to run on. We were looking for scalability of computing clusters and on-demand pricing. We were willing to tolerate some degree of faults through retries.</p><h3>Choosing the tech stack</h3><p>We explored multiple solutions. All major cloud vendors offer a production-grade orchestrator and an accompanying SDK. However, cloud-native experience limits local development and testing, ultimately reducing development velocity. We needed an infra-agnostic framework that runs on both local and cloud. We also wanted support for storing intra-pipeline artifacts, that is, artifacts produced by one step exclusively for some other step, as an intermediate output. Most cloud-native frameworks defer this responsibility to the end developer by requiring them to fiddle around with cloud-storage solutions manually.</p><h3>Metaflow as the application framework</h3><p>After some testing, we closed in on the <a href="https://metaflow.org/">Metaflow ML framework</a>. Metaflow’s philosophy of optimizing for the development experience of data scientists aligned closely with our own goals. In addition, the framework:</p><ul><li>Is infra-agnostic, so the same code runs as-is on both local and cloud</li><li>Provides an excellent interface for passing data artifacts between steps</li><li>Has excellent debugging capabilities</li></ul><p>Our data scientists can open a notebook and investigate any failed production or local run. They can look into artifacts produced by steps, their logs, and run time and resume the flow run from a single step to reproduce an issue. We optimized our infrastructure to leverage these features further.</p><p>However, Metaflow does have limitations in managing multi-version deployments and end-to-end automation, including deployment lifecycle, triggering, and monitoring. To fill these gaps, we have developed and continue refining in-house infrastructure layers over Metaflow.</p><h3>AWS Step Functions as the Orchestrator</h3><p>For the orchestrator, the decision path was much more straightforward. High availability requirements immediately prompted us to explore a cloud-native fully managed and/or serverless orchestrator. As most of our cloud infrastructure is in AWS, we decided to use <a href="https://aws.amazon.com/step-functions/">AWS Step Functions</a>, which ticks all the boxes. Additionally, Metaflow has native support for compiling the flow spec into a Step Functions state machine spec, so we did not have to do anything extra.</p><p>Though the most critical, the orchestrator is also the most inexpensive component in the stack. Despite running over multiple thousands of monthly pipelines for our customers, we are paying &lt;1% of our total MLOps infra cost on Step Functions. So far, we have not faced any scalability issues or downtimes due to Step Functions, so the high availability requirement is well fulfilled.</p><h3>AWS Batch over ECS Fargate as the compute cluster</h3><p>Our choice of the Metaflow framework forced us to choose <a href="https://aws.amazon.com/batch/">AWS Batch</a> over <a href="https://aws.amazon.com/ecs/">Amazon Elastic Container Sevice(ECS)</a> as our compute cluster. Though we had little choice in determining the abstraction layer, we have significant control over how AWS Batch provisions resources.</p><p>Initially, we gave in to the serverless vision by running AWS Batch over <a href="https://pages.awscloud.com/Application-Modernization-with-ECS-Fargate-No-PhD-Required_2022_0717-CON_OD.html">ECS Fargate</a>. AWS was fully managing everything from hardware to the control plane. We were only paying for the computing hours we used.</p><h3>Architecture overview</h3><p>To put everything in perspective, our architecture worked as follows:</p><ol><li>Our data scientists wrote dataflows in Python using Metaflow SDK.</li><li>Metaflow compiled the dataflow into a state machine spec suitable to run through AWS Step Functions.</li><li>AWS Step Functions sent job scheduling requests to AWS Batch.</li><li>AWS Batch, as a thin abstraction layer, defers task placement to Amazon ECS.</li></ol><p>By running our ECS cluster over Fargate, our tasks were placed on a fully managed hardware platform we did not have to manage.</p><figure><img alt="A schematic describing the overall cloud architecture of the system" src="https://cdn-images-1.medium.com/max/1024/1*qgTAKpTHpJEMqf_Vi_W0Jg.png" /><figcaption>A schematic describing the overall cloud architecture of the system</figcaption></figure><h3>Challenges with Fargate-based compute</h3><p>In a couple of months, we uncovered some difficulties with the compute cluster management. Firstly, Fargate costs more per vCPU per hour than a comparable EC2 instance. Secondly, as of writing, Fargate does not support GPUs, so steps that required GPUs could not be run. AWS is also silent on details on network bandwidth and disk bandwidth available to tasks running on Fargate. These details become important during the optimization phases.</p><p>But most importantly, we faced a unique challenge with Fargate related to the time it takes to pull the container image, which ultimately runs the Python code data scientists wrote. Due to a dense network of package dependencies, our Python container images are around 2GBs on average. Empirically it takes anywhere between 1–2 minutes for a Fargate task to start running due to the image pull time. The start delay was becoming a challenge for our MLOps workflows which are not compute-heavy but deal with things like writing to a feature store or doing lightweight processing.</p><h3>Switching from Fargate to EC2</h3><p>We decided to migrate from Fargate to <a href="https://aws.amazon.com/ec2/">Amazon EC2</a> for our MLOps workflows despite the expense of increased management.</p><p>The migration was challenging and required us to study AWS Batch internals and how Batch does the scheduling and autoscaling of EC2 instances responsively. Unfortunately, public documentation on Batch internals is scarce, so it was a game of trial and error.</p><p>After some experimenting, we solved our main challenge and decreased our image pull time by leveraging disk caching of images and enabling GPU. However, we occasionally see infrastructural errors on AWS, primarily related to networking issues. We have retries on all our workflow steps to mitigate these.</p><p>We aim to keep the instance utilization over 70% to beat Fargate regarding raw dollar cost.</p><h3>For the future</h3><p>As exciting as MLOps infrastructure work is, our unique requirement of running MLOps pipelines per customer also imposes challenges requiring specialized solutions. Our engineering team continuously tries to improve the infrastructure by optimizing for our use cases or adding new features keeping in mind our core tenets: automation, speed &amp; scalability. In future blog posts, we will talk about some of the solutions we’ve built — like our in-house caching layer to extract better performance while managing cost, a programmatic data contract layer between DS/ML and engineering teams, and much more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e630c99bae" width="1" height="1" alt=""><hr><p><a href="https://engblog.nirvanatech.com/orchestrating-data-science-workflows-at-scale-1e630c99bae">Orchestrating data science workflows at scale</a> was originally published in <a href="https://engblog.nirvanatech.com/">Nirvana Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Telematics Helps Keep Things Predictable: A Peek into Nirvana’s Safety Platform]]></title>
            <link>https://engblog.nirvanatech.com/how-telematics-helps-keep-things-predictable-a-peek-into-nirvanas-safety-platform-88b6c04fcb43?source=rss-63baa2e4fa64------2</link>
            <guid isPermaLink="false">https://medium.com/p/88b6c04fcb43</guid>
            <category><![CDATA[insurtech]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[telematics]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Nirvana]]></dc:creator>
            <pubDate>Fri, 16 Jun 2023 13:00:55 GMT</pubDate>
            <atom:updated>2023-06-16T13:00:55.391Z</atom:updated>
            <content:encoded><![CDATA[<p>By: <a href="https://www.linkedin.com/in/abhaymitra/">Abhay Mitra</a></p><p><em>Soaring insurance costs are an increasing concern for trucking. The unpredictability of renewal rates and the potential threat of being dropped entirely is making renewal a dreaded annual event. In-cab telematics can reduce accidents, improve efficiency, and help build more accurate and predictable risk models that can in turn reduce insurance costs.</em></p><p>Controlling and predicting insurance costs has become a top priority for trucking companies and their brokers. For fleets of all sizes, insurance is now a top three or four expense that is only getting more expensive due to higher claims and nuclear verdicts where juries’ awards surpass $10 million.[1]</p><p>Some companies are experiencing hikes of up to 50%. As you approach renewal, you have no idea how much more your coverage will cost next year and you’re in the dark as to whether or not a carrier may find reason to drop you. Finding new technologies to improve fleet safety as well identifying methods to predict future insurance costs is now crucial for industry survival and fleet carrier profitability.</p><p><strong>Assessing risk the old way</strong></p><p>Traditional insurers have historically based their prices on limited information, often using data from roadside inspections, investigations, and crash reports taken at a single point in time, which only captures 2–3% of your business operations. Insurers are basically looking at everything that is going wrong about your fleet; it is not a holistic picture of what you’re also doing right.</p><p>Most companies will have claims and accidents, but the frequency and severity varies. There are cases where a single inspection receives five violations, bumping up pricing for the next two years. There is little transparency on whether an incident or warning is going to be a big deal or not. With limited data points each year, there is no way of knowing what will impact your insurance rates at this year’s renewal and beyond.</p><p><strong>The benefits of using telematics</strong></p><p>In contrast to traditional risk-assessment methods, telematics offers a holistic view of your entire operation and can provide valuable insights into a fleet carrier’s real performance, beyond a snapshot in time. With telematics, it’s easy to capture real-time information about driver behavior, including aggressive acceleration, harsh braking, and erratic cornering.</p><p>Additionally, GPS technology through telematics enables live visibility into cab location and produces data to assess vehicle activity over time in areas of congestion, intersections, and neighborhoods to help ensure drivers are routinely taking the safest routes. Telematics also provides information that allows underwriters to contrast different fleet operations to see how their safety scores compare to their peers.</p><p><strong>Analyzing telematics data</strong></p><p>Nirvana’s Safety Platform takes in-cab telematics data and makes the numbers meaningful for companies and brokers through weekly updates and monthly newsletters. Nirvana’s Safety Platform first calculates the traditional CSA BASIC score for the fleet (See Chart 1). Then, it applies the “Nirvana Risk Score” to the mix in order to determine actual pricing (See Chart 2).</p><p>In Chart 2, a 50% threshold is average; but a 40% or less threshold is desirable. If you compare the two charts, the BASIC score makes the fleets look like a much higher risk because it rates risk factors based only on limited violations data.</p><p>The “Nirvana Risk Score” on the other hand includes more holistic data captured across time to create more accurate risk models, which factors in not only violations but also data points at which a company is succeeding, over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5mNn1VXOymPp3ehP" /><figcaption><em>Chart 1. Nirvana BASIC Scores Chart</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-KFzwqSRAUZ4zkRS" /><figcaption><em>Chart 2. Nirvana Risk Score</em></figcaption></figure><p>Nirvana’s Safety Platform also provides personalized recommendations to improve fleet safety, including a direct insurance impact that is classified into high, medium, and low categories. It also spells out what’s causing the identified issue, suggesting ways to resolve it, and calculating the insurance implications if it doesn’t get resolved.</p><p>This allows fleets to focus on specific areas that will move the needle the most in their safety scores. For example, if your fleet has a number of speeding violations that are driving up your BASIC score, you can address that specifically.</p><p><strong>Nirvana’s Safety Platform in action</strong></p><p>Fleet carriers that have found success on Nirvana’s Safety platform are the best illustration. Here are three creative ways to use Nirvana’s Safety Platform:</p><p>● <strong>Routes and routing.</strong> One fleet owner noticed a lot of their violations were coming from a single hot spot along a typical route. They decided to change this route to avoid that area in general. It didn’t create a big change in fuel or time to slightly change the route.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gtLVLk6ErUCBdgsJ" /><figcaption>Chart 3. Analysis of driving routes</figcaption></figure><p>● <strong>Repeat driver violations. </strong>A customer determined the same drivers often had the most moving violations, as they were listed as the top three violators over a period of time. The fleet carrier initiated a coaching program for drivers with repeated violations.</p><p>● <strong>Driver onboarding.</strong> One fleet owner was able to monitor a few new drivers during their first few weeks on the job to determine whether they needed more coaching, or perhaps if they were a bad hire altogether.</p><p>With real-time data thanks to telematics, Nirvana Safety Platform can predict and control insurance costs while building more accurate risk models. It helps fleet carriers turn data into actionable insights to reduce accidents and other costly violations.</p><p>For more information about Nirvana’s Safety Platform, please visit <a href="https://www.nirvanatech.com/safety">Nirvana Insurance</a>.</p><p>[1] Wall Street Journal.com “Surging Truck Insurance Rates Hit Freight Operators”, January 13, 2020.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88b6c04fcb43" width="1" height="1" alt=""><hr><p><a href="https://engblog.nirvanatech.com/how-telematics-helps-keep-things-predictable-a-peek-into-nirvanas-safety-platform-88b6c04fcb43">How Telematics Helps Keep Things Predictable: A Peek into Nirvana’s Safety Platform</a> was originally published in <a href="https://engblog.nirvanatech.com/">Nirvana Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>