<?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 Yingkun Bai on Medium]]></title>
        <description><![CDATA[Stories by Yingkun Bai on Medium]]></description>
        <link>https://medium.com/@baiyingkun?source=rss-fb5b30c209a0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yQTohvdSGAm8G6IzYqIufA.png</url>
            <title>Stories by Yingkun Bai on Medium</title>
            <link>https://medium.com/@baiyingkun?source=rss-fb5b30c209a0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 16:46:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@baiyingkun/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[Building High-Performance Data Pipelines with PostgreSQL and Hibernate: Lessons from Swissquote.]]></title>
            <link>https://medium.com/swissquote-engineering/building-high-performance-data-pipelines-with-postgresql-and-hibernate-lessons-from-swissquote-4493e27f496b?source=rss-fb5b30c209a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4493e27f496b</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[hibernate]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[lessons-learned]]></category>
            <dc:creator><![CDATA[Yingkun Bai]]></dc:creator>
            <pubDate>Mon, 17 Feb 2025 12:37:01 GMT</pubDate>
            <atom:updated>2025-02-17T12:37:01.472Z</atom:updated>
            <content:encoded><![CDATA[<p>This article shares insights from my talk at Voxxed Day Ticino 2025, focusing on practical strategies for achieving high performance in data-intensive environments using PostgreSQL and Hibernate.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FoG916NSfT7M%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DoG916NSfT7M&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FoG916NSfT7M%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/101e007603d41579f526cd438520c1b2/href">https://medium.com/media/101e007603d41579f526cd438520c1b2/href</a></iframe><p>Hi! I’m Yingkun, a software engineer at Swissquote, working in a team dedicated to financial reference data integration. In this article, we will explore techniques like Hibernate StatelessSessions, JDBC batching, and query streaming, highlight common pitfalls, and outline strategies to overcome them. Lastly, we’ll touch on our future vision for evolving this pipeline.</p><h4><strong>Table of Contents</strong></h4><p>· <a href="#045a">1. Introduction</a><br>· <a href="#d8e4">2. The Most Important Lessons We Learned About PostgreSQL </a><br>· <a href="#a276">3. How We Write Efficiently into PostgreSQL</a><br>· <a href="#28dc">4. How We Stream Data Efficiently from PostgreSQL</a><br>· <a href="#488b">5. Future Directions</a><br>· <a href="#0968">6. Conclusion</a></p><h3>1. Introduction</h3><p>In today’s data-driven world, efficiently processing and managing large volumes of data is critical for success across industries. Data pipelines are the backbone of businesses relying on timely, accurate information to power decision-making, operational workflows, and customer-facing services.</p><p>At <strong>Swissquote</strong>, we provide access to over 50 stock markets, enabling seamless trading for over 4 <strong>million products</strong>, including stocks, ETFs, cryptocurrencies, and more. Behind this seamless trading experience lies a significant challenge: ensuring that the data for these securities is accurate, up-to-date, and properly organized.</p><p>My team manages a robust data pipeline that processes financial reference data through several key stages:</p><ul><li><strong>Retrieval</strong>: Gathering information from external providers in diverse formats.</li><li><strong>Validation</strong>: Ensuring accuracy, completeness, and consistency.</li><li><strong>Normalization</strong>: Aligning data to our internal financial data model.</li><li><strong>Storage</strong>: Efficiently storing data for organizational accessibility.</li><li><strong>Delivery</strong>: Distributing data in formats tailored to internal consumers.</li></ul><p>Despite differences in business needs, these challenges are common across industries such as banking, healthcare, and financial services. I hope you can apply some of our data-pipeline recipes that worked for us.</p><h4>1.1 The Reference Data Product Factory in SQ</h4><p>Our system relies on a <strong>two-tier architecture</strong> consisting of a <strong>data lake</strong> and a <strong>data warehouse</strong> to manage our reference data pipeline. Each tier serves a distinct purpose: the <strong>data lake</strong> acts as the <strong>source of truth for raw provider data. </strong>In contrast, the <strong>data warehouse</strong> serves as the <strong>source of truth for normalized data</strong>, structured according to our internal financial instrument model.</p><p>This design addresses our key operational needs:</p><ul><li><strong>Auditability</strong>: By separating raw and normalized data, we can easily trace issues to specific layers, helping us identify whether the problem lies with the provider data or our normalization processes.</li><li><strong>Modularity</strong>: Changes to providers or upstream sources are confined to the data lake layer, minimizing the impact on the rest of the system.</li></ul><p>Together, these tiers form the foundation of our use case and are the focus of today’s discussion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9VUvxMAw0xlpY5TdgQ-2Yg.png" /><figcaption>Two tier data processing architecture</figcaption></figure><p>In building this system, we’ve embraced the idea that <strong>context and scope are critical</strong> to defining an effective solution. As economist Thomas Sowell put it:</p><blockquote><em>“There are no solutions; there are only trade-offs. You try to get the best trade-off you can get, and that’s all you can hope for.”</em></blockquote><p>This mindset has shaped our best practices and strategies for managing bulk data, integrating external sources, and maintaining system performance.</p><h4>1.2 The Main Challenges of Our Bulk Data Processing System</h4><p>With the architecture above, we have identified three primary challenges that define our pipeline, often referred to as the “3 Vs” by our team:</p><ol><li><strong>Volume</strong>: Managing over 500 million daily database operations for 4 million financial instruments, each involving 200+ data points from diverse providers.</li><li><strong>Velocity</strong>: Handling updates before market openings (8–9 a.m. CET in Europe and 2–3 p.m. EST in the US) while supporting 24-hour trading systems, which demand near real-time updates.</li><li><strong>Variety</strong>: Integrating data from external vendors in JSON, CSV, XML, and proprietary formats, requiring a highly flexible and adaptable system.</li></ol><p>Addressing these challenges is key to building robust data systems that cater to dynamic data demands and ensure up-to-date information.</p><h3>2. The Most Important Lessons We Learned About PostgreSQL</h3><p>Our journey with PostgreSQL began in 2015. We were driven by the need to handle semi-structured data from providers with evolving formats, the challenge of “<strong>Variety</strong>” mentioned previously. At the time, the version of Oracle we were using lacked advanced features like JSON/JSONB support, prompting us to explore alternative database solutions.</p><p>PostgreSQL stood out as an <strong>open-source, cost-efficient solution</strong> that supports advanced data types (e.g., JSON, ARRAYS, ENUM), robust indexing, and seamless integration with Hibernate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*fPYz2mqGhMP9iOuPaETEnw.png" /></figure><p>With over seven years of production experience, PostgreSQL has become the backbone of our data pipeline. Maintaining its health requires not only proper configuration but also an understanding of how application behavior influences critical processes like <strong>VACUUM</strong>.</p><p>In the following section of this chapter, we’ll dive into how VACUUM works, why it is essential for PostgreSQL’s performance, and the challenges that arise when it is not properly configured or executed. Later in the article, we’ll also explore how design choices, such as long-running transactions or inefficient query patterns, can impact the VACUUM process — and how developers can avoid these pitfalls.</p><h4>2.1 MVCC and VACUUM in PostgreSQL</h4><p>Unlike some traditional databases, PostgreSQL’s <strong>MVCC </strong>(Multi-Version Concurrency Control) follows an append-only approach, where updates create new row versions instead of modifying existing ones. This design supports non-blocking reads and high concurrency but leads to <strong>dead tuples</strong> (outdated row versions) accumulating in tables, a phenomenon known as <strong>table bloat</strong>.</p><p><strong>(1) How VACUUM works</strong></p><p>To address this, PostgreSQL relies on the <strong>VACUUM process</strong>. VACUUM reclaims disk space by removing dead tuples and updates the visibility map to enhance query efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*LxMRXMLfI5p_welmd0hi7g.png" /><figcaption><a href="https://www.postgresql.eu/events/pgconfeu2019/sessions/session/2748/slides/242/vacuum_future_pgconf_eu_2019.pdf">https://www.postgresql.eu/events/pgconfeu2019/sessions/session/2748/slides/242/vacuum_future_pgconf_eu_2019.pdf</a></figcaption></figure><p>The diagram above illustrates this process. Before running VACUUM, dead rows consume valuable space in the database, degrading performance. Once VACUUM is executed, this space is reclaimed, ensuring efficient data access and storage.</p><p>VACUUM must be configured appropriately, either through <strong>autovacuum</strong> or <strong>manual execution</strong>:</p><ul><li><strong>Autovacuum</strong>: PostgreSQL’s built-in background process automatically handles routine maintenance tasks.</li><li><strong>Manual VACUUM</strong>: In systems with heavy workloads or specific performance requirements, manual VACUUM operations may be necessary to ensure timely cleanup.</li></ul><p>Delays in VACUUM can degrade performance and, in extreme cases, even cause database failure.</p><p><strong>(2) Implications for Developers</strong></p><p>While VACUUM might seem like a low-level database feature, it has significant implications for application development. For example:</p><ul><li><strong>Long-Running Transactions</strong>: Applications that hold transactions open for extended periods can block VACUUM, leading to table bloat and degraded performance.</li><li><strong>Efficient Query Design</strong>: Developers must design queries to minimize long-running transactions and avoid unnecessary dead tuple accumulation.</li></ul><p>By understanding how their applications influence VACUUM, developers can ensure their systems complement PostgreSQL’s internal processes, maintaining both performance and stability.</p><h3>3. How We Write Efficiently into PostgreSQL</h3><p>With a good understanding of PostgreSQL’s MVCC and VACUUM, we can return to the Java world and explore the technical aspects of building a high-performance data pipeline.</p><p>The following sections will cover JDBC batching, Hibernate Stateless Session, and generating unique identifiers. We’ll try to explain why we chose our final tech stack.</p><p><strong>Here is an overview of this chapter:</strong><br> ∘ <a href="#5cb9">3.1 Understanding JDBC and Batching</a><br> ∘ <a href="#2268">3.2 Using JDBC Batching with Hibernate</a><br> ∘ <a href="#1e36">3.3 Choosing a Proper Batch Size</a><br> ∘ <a href="#8668">3.4 Generating Identifiers Efficiently</a></p><h4>3.1 Understanding JDBC and Batching</h4><p>Regardless of the framework you’re using — whether it’s Spring Data JPA, MyBatis, or others — JDBC serves as the foundational layer for database interactions. Importantly, batching occurs <strong>exclusively</strong> at the JDBC level, making it a critical mechanism for optimizing performance in database operations.</p><blockquote>Batching works by grouping multiple SQL operations into a single round-trip to the database, reducing overhead and significantly improving performance, especially in scenarios involving large volumes of data.</blockquote><p>Below is a quick overview of the JDBC architecture and JDBC batching processing in a Java application, highlighting its role in database interactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9P3QOFIGhqA_2hg_pHYTw.png" /><figcaption>JDBC Architecture</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-j-ZxrQQU2JsXf7i-op-AQ.png" /><figcaption>Left: No Batching | Right: Batching with Grouped Query</figcaption></figure><h4>3.2 Using JDBC Batching with Hibernate</h4><p>Batching is a powerful feature provided by JDBC that can significantly improve database performance but is <strong>not enabled by default</strong>. While it is possible to use batching directly with raw JDBC, doing so often makes the code <strong>tedious and overly complicated</strong>, requiring developers to handle low-level details such as managing batch sizes, tracking statements, and handling errors manually. This complexity can be a barrier to implementing efficient batching in applications.</p><p>Here is a simple example of using raw JDBC to do batching:</p><pre>private static void executeInBatches(Connection connection) throws SQLException {<br>    String insertQuery = NativeJdbcBatchingExample.INSERT_SQL_QUERY;<br>    int batchSize = 50;  // Define the batch size<br>    int count = 0;<br><br>    try (PreparedStatement ps = connection.prepareStatement(insertQuery)) {<br>        for (int i = 1; i &lt;= 1000; i++) {<br>            ps.setInt(1, i);<br>            ps.setBigDecimal(2, new java.math.BigDecimal(&quot;100.00&quot;));<br>            ps.addBatch();  // Add the record to the batch<br><br>            if (++count % batchSize == 0) {<br>                ps.executeBatch();  // Execute the batch every 50 records<br>                connection.commit();  // Commit the transaction<br>                log.info(&quot;Batch executed and committed.&quot;);<br>            }<br>        }<br><br>        // Execute any remaining records in the batch<br>        ps.executeBatch();<br>        connection.commit();<br>        log.info(&quot;Final batch executed and committed.&quot;);<br><br>    } catch (SQLException e) {<br>        connection.rollback();  // Rollback in case of error<br>        log.error(&quot;SQL Exception: {}&quot;, e.getMessage());<br>    }<br>}</pre><p>To address this, we rely on <strong>Hibernate</strong>, which abstracts much of the complexity and makes enabling batching straightforward.</p><p><strong>3.2.1 Enabling JDBC batching in Hibernate</strong></p><p>There are two primary ways to enable JDBC batching in Hibernate:</p><p><strong>Global configuration(applied across all sessions):</strong></p><pre>hibernate.jdbc.batch_size=20</pre><p><strong>Session-level configuration(applied to specific sessions)</strong>:</p><pre>StatelessSession session = sessionFactory.openStatelessSession();<br>session.setJdbcBatchSize(50);</pre><p><strong>3.2.2 Preferring Hibernate StatelessSession to Traditional Session</strong></p><p>For bulk operations, we prefer using <strong>StatelessSession</strong> over Hibernate’s default Session, which operates within a Persistence Context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Y66l3qCCtjVmVa71jixYA.png" /><figcaption>Persistence Context</figcaption></figure><p>While the Persistence Context provides caching and automatic dirty checking — useful in transactional applications — it introduces unnecessary overhead in bulk operations by tracking entity states in memory. This overhead makes batch inserts and updates less efficient.</p><p>This is where <strong>StatelessSession</strong> comes in. By bypassing the Persistence Context, it avoids caching and dirty checking, making it far more memory-efficient and optimized for high-throughput bulk operations. It operates closer to the database layer, reducing resource consumption and improving performance.</p><p><strong>3.2.3 Leveraging the Simplicity of Native Hibernate API</strong></p><p>Since our bulk operations primarily rely on StatelessSession, the <a href="https://docs.jboss.org/hibernate/orm/6.6/introduction/html_single/Hibernate_Introduction.html#hibernate-and-jpa"><strong>Hibernate Native API</strong> </a>(i.e., directly using SessionFactory and Session without JPA) is a natural choice for our application. By bypassing JPA’s EntityManager, the native API gives us direct access to SessionFactory, enabling effortless creation of StatelessSession instances. This optimizes our workflow for large-scale data processing by reducing overhead and improving performance.</p><p>The following example demonstrates how to use Hibernate StatelessSession with the Hibernate Native API for efficient batch insertion:</p><pre>public void createEntitiesInBatchSize(int total, int batchSize) {<br>    // Generate a list of entities with unique identifiers<br>    List&lt;UuidV6Entity&gt; uuidV6EntityList = IntStream.range(1, total + 1)<br>            .mapToObj(integer -&gt; new UuidV6Entity(generateRandomString()))<br>            .toList();<br>    <br>    // Open a StatelessSession for efficient bulk operations<br>    try (StatelessSession statelessSession = sessionFactory.openStatelessSession()) {<br>        // Set the JDBC batch size for optimal batching<br>        statelessSession.setJdbcBatchSize(batchSize);<br><br>        // Begin a transaction to group operations<br>        Transaction transaction = statelessSession.beginTransaction();<br><br>        // Insert entities into the database<br>        uuidV6EntityList.forEach(statelessSession::insert);<br><br>        // Commit the transaction to persist changes<br>        transaction.commit();<br>    }<br>}</pre><h4>3.3 Choosing a Proper Batch Size</h4><p>In the above code example, we have one variable to tune — Batch size. Batch size not only affects performance but also interacts with transaction management, impacting database health and efficiency.</p><p><em>But is a larger batch size always better?</em></p><p>To explore this, we ran a <a href="https://github.com/yingkun-bai/hibernate-postgres/blob/bb03390e28168a5f20231c58dbb5934d22a61af6/demo/src/test/java/app/BatchingTest.java#L40-L58">unit test</a> with varying record counts and batch sizes. The results provided valuable insights into the impact of batching on performance, particularly highlighting the high execution time when batch size is set to 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*iwsAU_jZ35Ez76XyY1r9oA.png" /><figcaption>Performance Impact of Different Batch Sizes</figcaption></figure><p><strong>Key Notes:</strong></p><ol><li><strong>Larger Batch Sizes and Performance</strong>: Bigger batches reduce database round-trips, improving performance. However, beyond a certain point, the benefits plateau or reverse as I/O bottlenecks emerge. Once the database reaches its capacity, larger batches lead to diminishing returns and may degrade performance due to higher memory usage and transaction overhead.</li><li><strong>Memory Usage</strong>: On the database side, larger batches consume more memory, potentially causing resource contention when the database is under heavy load. On the application side, batching stores operations in memory until they’re executed. Oversized batches can lead to OutOfMemoryError or increased memory pressure on the JVM.</li><li><strong>Error Handling</strong>: Managing errors with larger batches is more challenging. For example, if a batch size of 1,000 fails on the 999th operation, rolling back or retrying the entire batch can be time-consuming. Large batch sizes increase the complexity of handling partial commits or selectively retrying failed operations.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9dQuvYvDCmiF9w7Q8b8HFA.png" /><figcaption>Different Database and Batch Size Relationship</figcaption></figure><h4>3.4 Generating Identifiers Efficiently</h4><p>In this final section on efficient writing, we focus on identifier generation — a key factor in ensuring performance and scalability in our data pipeline.</p><p>At Swissquote, we use <strong>ISIN</strong> (International Securities Identification Number) as the natural ID for our tradable products. ISIN is a 12-character alphanumeric code used globally to identify financial securities, such as stocks, bonds, and other instruments.</p><p>Initially, Swissquote focused on share trading, where ISINs were standard and readily available. However, as we expanded into options, futures, swaps, commodities (e.g., gold, oil), and currencies, we encountered a significantly larger set of instruments without ISINs.</p><p>To maintain consistency across our systems, we generate internal identifiers that follow the same structured principles as ISINs. Given our data model’s focus on financial instruments, selecting the right ID generation strategy is crucial for pipeline performance and scalability.</p><p><strong>ID Generation Strategies in Hibernate</strong></p><p>Hibernate implements JPA standard and offers two primary ways for assigning IDs to an entity:</p><ol><li><strong><em>Assigned IDs</em></strong><em>:</em> Manually set by the application. While simple, this approach requires meticulous management to avoid duplication or conflicts.</li><li><strong><em>Generated IDs</em></strong><em>:</em> Automatically generated by the database or persistence provider (@GeneratedValue). These are more scalable and less error-prone, but the choice of generation strategy significantly impacts performance.</li></ol><p>For generated IDs, Hibernate offers JPA standard generation strategies and also user-defined Generators, with more explanation <a href="https://docs.jboss.org/hibernate/orm/6.6/introduction/html_single/Hibernate_Introduction.html#generated-identifiers">here</a>. However, not all of them are suitable in bulk data scenarios.</p><ul><li><strong>❌IDENTITY</strong>: IDs are generated after insert. This approach prevents JDBC batching, making it unsuitable for batch processing.</li><li><strong>⚠️SEQUENCE</strong>: IDs are fetched before insert, allowing batching. It’s a reliable choice, but the <strong>allocation size</strong> must align with the sequence’s increment if you’re working with a database schema managed outside Hibernate.</li></ul><pre>@Id<br>@GeneratedValue(strategy=SEQUENCE, generator=&quot;bookSeq&quot;)  // reference to generator defined below<br>@SequenceGenerator(name=&quot;bookSeq&quot;, sequenceName=&quot;seq_book&quot;, initialValue = 5, allocationSize=10)<br>Long id;</pre><ul><li>⚠️ <strong>UUID</strong>: By default, Hibernate uses <strong>random UUIDs (UUIDv4)</strong>, which can lead to <strong>poor index performance</strong> with B-trees due to their non-sequential nature.</li><li>✅ <strong>If UUIDs are required: </strong>configure Hibernate to use time-based UUIDs (e.g. UUIDv1) for better index locality and improved insertion performance.</li></ul><pre>@Id<br>@GeneratedValue<br>@UuidGenerator(style = UuidGenerator.Style.TIME) // Use UUIDv1 (time-based)<br>private UUID id;</pre><ul><li><strong>❌TABLE</strong>: IDs are generated using a separate table. This approach is inefficient and prone to locking issues.</li><li><strong>❌AUTO</strong>: Behavior depends on the database and may default to IDENTITY, SEQUENCE, or TABLE. Its variability makes it less predictable and often less optimal.</li></ul><p><strong>🚀 Recommended ID Generation Strategy</strong></p><p>Based on our experience, we recommend <em>A </em><strong><em>hybrid</em></strong><em> approach combining </em><strong><em>sequence</em></strong><em>-based ID generation with </em><strong><em>assigned</em></strong><em> IDs.</em></p><p>👉🏼<strong>How it works:</strong></p><p>(1) We pre-fetch a batch of sequence values using a dedicated sequence* in PostgreSQL for ISIN generation::</p><pre>SELECT nextval(&#39;sequence_name&#39;) as val<br>FROM generate_series(1, num);</pre><p><em>*Using a dedicated sequence ensures that ISINs remain unique across the entire system.</em></p><p>(2) Once the sequence values are fetched, we <strong>apply additional formatting or transformations</strong> before assigning them to entities.</p><p>(3) With IDs pre-generated and assigned, entities can be inserted in bulk efficiently.</p><p>This method eliminates the key limitations of other strategies while ensuring JDBC batching efficiency and globally unique identifiers.</p><h3>4. How We Stream Data Efficiently from PostgreSQL</h3><p>After our detailed discussion about writing, now let’s see how to better read from PostgreSQL — an equally crucial part of our data pipeline. Given our system’s scale, data <strong>retrieval</strong> must be optimized to handle the “3 Vs” mentioned earlier. To be specific:</p><ul><li><strong>Volume</strong>: Streaming large datasets efficiently without overwhelming memory.</li><li><strong>Velocity</strong>: Ensuring fast query response times, especially for time-sensitive market data updates.</li><li><strong>Variety</strong>: Handling diverse data formats and complex query patterns without unnecessary overhead.</li></ul><p>However, optimizing for these qualities requires avoiding common pitfalls and applying best practices tailored to PostgreSQL’s architecture.</p><p><strong>Here is an overview of this chapter:</strong><br> ∘ <a href="#6a3f">4.1 Some Common Pitfalls</a><br> ∘ <a href="#cd45">4.2 Tactics to Consider for Better Reading</a></p><h4>4.1 Some Common Pitfalls</h4><p><strong>4.1.1 Avoid the Fetch Size Pitfall</strong></p><p>The first thing we would like to address is the pitfall around fetch size in the PostgreSQL JDBC driver.</p><p>By default, PostgreSQL drivers fetch all query results at once, leading to memory overhead. Setting an appropriate fetch size ensures true streaming behavior.</p><p>The following three streaming results have the same memory footprint, as no fetch size is specified. Though it seems we’re doing streaming in the first two, in reality, all entries from the BigTable will be loaded:</p><pre>statelessSession.createQuery(&quot;from BigTable&quot;, BigTable.class).stream()<br>statelessSession.createQuery(&quot;from BigTable&quot;, BigTable.class).getResultStream()<br>statelessSession.createQuery(&quot;from BigTable&quot;, BigTable.class).getResultList().stream()</pre><blockquote>Always set an appropriate fetch size when streaming or processing large datasets to avoid memory overhead and ensure true streaming behavior.</blockquote><p>Let’s compare the impact of using a <strong>fetch size</strong> versus not specifying one. You can find the test details in our <a href="https://github.com/yingkun-bai/hibernate-postgres/blob/main/demo/src/test/java/app/FetchingPerformanceTest.java#L26-L44">repository</a>. In this comparison, we profile two scenarios where the same code is used to stream data from a large table, but with one key difference:</p><ul><li>In the first test, no <strong>fetch size</strong> is specified.</li><li>In the second test, a <strong>fetch size of 100</strong> is configured.</li></ul><p>For this test, we simulate a <strong>3,379 MB table</strong> comparable in size to our real-world datasets used for managing our financial instruments. This test helps illustrate the memory and performance impact of different query configurations in PostgreSQL</p><p>The two profiling images can be seen below, with clear memory consumption differences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*leLpoUNfsSNe1atX5cNIGA.png" /><figcaption>Left: without fetech size. Right: with fetch size of 100</figcaption></figure><p><strong>4.1.2 Hidden Long-Running Transactions with Streaming</strong></p><p>Specifying fetch size is not enough to make our application safe when streaming from PostgreSQL. See the following example below:</p><pre><br>private Stream&lt;UuidV6Entity&gt; generateSourceStream() {<br>    StatelessSession session = sessionFactory.openStatelessSession();<br>    return session.createQuery(&quot;FROM UuidV6Entity&quot;, UuidV6Entity.class)<br>                  .setFetchSize(100)<br>                  .stream()<br>                  .onClose(session::close); // Ensure session closes when the stream is closed<br>}<br><br>public void processStreamWithSlowIntermediary() {<br>    try (Stream&lt;UuidV6Entity&gt; stream = generateSourceStream().parallel()) { <br>        // Use parallel stream for concurrent processing<br>        stream.forEach(this::processEntity);<br>    }<br>}<br><br>private void processEntity(UuidV6Entity entity) {<br>    try {<br>        log.info(&quot;Processing entity: {}&quot;, entity.getId());<br>        // Simulate a slow I/O operation with sleep (can be replaced with real I/O task)<br>        Thread.sleep(1000);<br>    } catch (InterruptedException e) {<br>        Thread.currentThread().interrupt();<br>        log.error(&quot;Thread was interrupted while processing entity: {}&quot;, entity.getId(), e);<br>    }<br>}</pre><p>Imagine that we have 10 billion entries to process. Even though we specify fetch size and don’t load everything in our memory, will the application remain stable during processing?</p><p>Unfortunately, not really. There’s another risk. StatelessSession remains open until processing completes. Even though we are not explicitly specifying a transaction, Hibernate will wrap a transaction for this query. This transaction will be kept open, blocking all vacuum operations after the starting point.</p><p>This actually happened in our production in 2022. We observed significant table bloat in one database instance due to a blocked VACUUM process by one application’s long-running transaction. This led us to reassess our code when designing our applications. We’ll go over the solution in the tactics section later.</p><p><strong>4.1.3 Hidden Transaction Leaking in StatelessSession</strong></p><p>There’s another problem around transactions in the above code snippets. The hidden transaction leaks.</p><p>Our code would “work” without declaring transactions explicitly, as it’s a read-only operation. But when using Hibernate’s StatelessSession, failing to manage transactions explicitly can cause them to remain open even after the session is closed, leading to resource leaks and potentially blocking maintenance operations like PostgreSQL&#39;s VACUUM.</p><p>Here is how we can modify the code to include explicit transactions:</p><pre>private Stream&lt;UuidV6Entity&gt; generateSourceStream() {<br>    StatelessSession session = sessionFactory.openStatelessSession();<br>    Transaction transaction = session.beginTransaction(); // Begin transaction explicitly<br>    return session.createQuery(&quot;FROM UuidV6Entity&quot;, UuidV6Entity.class)<br>                  .stream()<br>                  .onClose(() -&gt; {<br>                      transaction.commit(); // Commit transaction explicitly<br>                      session.close();      // Ensure session is closed<br>                  });<br>}</pre><h4>4.2 Tactics to Consider for Better Reading</h4><p>Now that we’ve explored common pitfalls, let’s shift our focus to practical tactics that can help avoid these issues and enhance performance. In this section, we’ll cover two key strategies to mitigate pitfalls, followed by an approach to improve performance through indexing.</p><p><strong>4.2.1 Offloading your stream with Chronicle API</strong></p><p>One effective tactic is offloading streamed data into a secondary storage mechanism, allowing the database connection to close early and streaming to continue from an intermediary storage. A powerful tool for this purpose is <a href="https://github.com/OpenHFT/Chronicle-Map"><strong>Chronicle Map</strong></a>, which utilizes <strong>memory-mapped files</strong> to efficiently store and access large datasets.</p><p>With Java 21, new features further enhance memory-mapped file handling, potentially offering more streamlined and efficient ways to handle large-scale data ingestion.</p><p>We adopted this solution to address <strong>out-of-memory (OOM) issues</strong> that arose while ingesting a large file from a provider. The sudden surge in load from the source file overwhelmed our system’s memory, causing frequent failures during direct ingestion. By offloading the data into <strong>Chronicle Map</strong>, we decoupled the database connection and efficiently processed the file without exceeding memory limits. This approach not only resolved the OOM issues but also significantly improved the stability of our ingestion workflow. Additionally, it enhanced our system’s flexibility in handling the <strong>“Variety” challenge</strong> of our architecture, allowing us to better adapt to diverse data formats and sources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*oCZR6D7_E_AD83JPmjq9_Q.png" /></figure><ul><li><strong>Benefits</strong>: Efficient use of memory-mapped files and asynchronous disk flushing.</li><li><strong>Challenges</strong>: Requires upfront sizing, custom serialization, and consideration for OS paging effects.</li></ul><p>For a concrete example, refer to the implementation in our code <a href="https://github.com/yingkun-bai/hibernate-postgres/blob/a3a4cbdbaf8d86fb678aa45aeb1a5252ff212448/demo/src/main/java/app/ReactiveStreamProcessingExamples.java#L80">repository</a>. While Chronicle API offers significant advantages, it comes with a learning curve. We recommend thoroughly reviewing its <a href="https://chronicle.software/">official documentation</a> and understanding its trade-offs before integrating it into your project.</p><p><strong>4.2.2 Sharding your upstream into smaller substreams</strong></p><p>Sharding is a widely used technique for breaking large datasets into <strong>smaller, more manageable subsets</strong> for parallel processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*oHTJC8RHaV5iWvSs95axIg.png" /></figure><p>We adopted this approach recently (January 2025) to resolve a critical production incident. One of our applications, responsible for processing <strong>60 million updates</strong>, faced severe challenges, including <strong>long-running transactions</strong>, <strong>out-of-memory (OOM) errors</strong>, and <strong>system degradation</strong>. The processing time ballooned to over six hours as the load overwhelmed the database and the application server.</p><p>To address this, we <strong>sharded the 60 million entries into smaller partitions</strong> and processed them independently. Each shard was handled as a separate “substream,” allowing for parallel processing with reduced contention. By doing this, we completed the entire operation in under <strong>20 minutes</strong> — a significant improvement. This approach shortened transaction durations, minimized resource contention, and stabilized the overall system.</p><p>This example demonstrates how <strong>sharding</strong> can effectively tackle large-scale data processing challenges and optimize database and application performance. It highlights the practical impact of sharding in addressing these challenges and optimizing database and application performance.</p><p><strong>4.2.3 Benefiting from Advanced Data Types and Indexing</strong></p><p>Finally, we would like to examine PostgreSQL’s <strong>advanced indexing</strong>, which makes it easier to optimize data retrieval from another perspective.</p><p>Have you encountered scenarios where searching within a JSON column slows down as the dataset grows? <a href="https://www.postgresql.org/docs/current/gin.html">GIN index</a> is here to help. It’s best used for JSONB filtering and full-text search.</p><p>Let’s see together a concrete example. Consider a table that stores product metadata in a JSONB column:</p><pre>CREATE TABLE product_data (<br>    id SERIAL PRIMARY KEY,<br>    product_info JSONB<br>);</pre><p>Without an index, querying this table for products with a specific attribute (e.g., category) becomes slower as the dataset grows:</p><pre>SELECT * <br>FROM product_data<br>WHERE product_info -&gt;&gt; &#39;category&#39; = &#39;stocks&#39;;</pre><p>If the table contains millions of rows, this query will result in a sequential scan, which is time-consuming. By adding a GIN index, we can dramatically improve the performance of such queries:</p><pre>CREATE INDEX idx_product_category <br>ON product_data <br>USING gin (product_info);</pre><p>After creating the index, PostgreSQL can quickly locate the rows matching the condition without scanning the entire table:</p><pre>EXPLAIN ANALYZE<br>SELECT * <br>FROM product_data<br>WHERE product_info @&gt; &#39;{&quot;category&quot;: &quot;stocks&quot;}&#39;;</pre><p>The @&gt; operator checks if the JSONB column contains a specified key-value pair. With the GIN index, the query plan will show a significant reduction in execution time due to efficient index usage.</p><p>This example illustrates the impact of GIN indexing and provides a practical context for its use. However, note that GIN indexes often consume significantly more space compared to standard B-tree indexes. You can read more here: <a href="https://www.postgresql.org/docs/17/gin.html">https://www.postgresql.org/docs/17/gin.html</a></p><h3>5. Future Directions</h3><p>Though we have a solid system ensuring stable daily operations, we are continuously exploring <strong>new architectures</strong> and <strong>advanced technologies</strong> to further enhance performance and scalability. Below are some of our current projects:</p><ul><li><strong>PG Bouncer</strong>: Investigating server-side connection pooling to overcome PostgreSQL’s process-based connection model. This optimization improves resource usage and scalability<em>.</em></li><li><strong>Debezium with Kafka Connect</strong>: Adopting a log-based event-driven architecture to reduce direct database load, enabling more efficient data synchronization and real-time processing.</li><li><strong>System Improvements</strong>: Continuously refining performance and scalability to meet growing operational demands.</li></ul><h3>6. Conclusion</h3><p>Building high-performance data pipelines is both a challenge and an opportunity. At Swissquote, we’ve tackled these challenges by leveraging <strong>PostgreSQL</strong>’s advanced features, optimizing data ingestion and storage through <strong>JDBC batching</strong> and <strong>Hibernate StatelessSessions</strong>, and avoiding common mistakes.</p><p>Looking ahead, we’re excited to adopt <strong>event-driven architectures</strong> using tools like <strong>Kafka Connect with Debezium </strong>and explore <strong>PG Bouncer</strong> for better connection pooling. These advancements will help us scale to meet the growing demands of tomorrow’s fast-paced, data-driven world.</p><p>For all codes mentioned above, visit the GitHub repository <a href="https://github.com/yingkun-bai/hibernate-postgres">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4493e27f496b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swissquote-engineering/building-high-performance-data-pipelines-with-postgresql-and-hibernate-lessons-from-swissquote-4493e27f496b">Building High-Performance Data Pipelines with PostgreSQL and Hibernate: Lessons from Swissquote.</a> was originally published in <a href="https://medium.com/swissquote-engineering">Swissquote Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>