Streaming Database Exports in Spring Boot

Exporting millions of rows from a database looks simple until the application runs out of memory or exhausts its connection pool. Loading the entire result set into a List is rarely viable at scale.

This guide shows how to stream large database exports in Spring Boot without breaking the app: fetch-size configuration, read-only transactions, connection pool management, delivery via StreamingResponseBody, and keyset pagination as the fallback when connection capacity is tight.

Why Large Exports Fail

A naive export loads every row into memory before writing the response:

List<Order> orders = orderRepository.findAll();
return orders;

At a few million rows, five things go wrong at once:

  • Memory exhaustion. Every entity instance consumes heap. A large result set triggers OutOfMemoryError or long GC pauses.
  • Slow first byte. The client waits until the entire result set is loaded and serialized before receiving any data.
  • Long-held connections. The connection is checked out for the whole export, shrinking capacity for other requests.
  • Timeouts. Proxies, load balancers, and HTTP clients give up before the response finishes.
  • Database pressure. One large query consumes database memory, temp storage, and I/O.

Export Approaches Compared

Approach Memory Connection Best for
Load all rows into a list High Short Small datasets only
Offset pagination Low per page Short per page Moderate datasets, stable ordering
Keyset pagination Low per page Short per page Large datasets with indexed sort keys
JPA stream Low Held during iteration Server-side streaming, supported drivers
Plain JDBC streaming Low Held during iteration Maximum control

Streaming is powerful, but it holds a database connection open while rows are consumed. That’s the trade-off to manage.

Streaming With Spring Data JPA

Spring Data JPA supports Stream<T> as a query return type. The stream must be consumed inside a transaction and closed properly.

Repository method

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.stream.Stream;

public interface OrderRepository extends JpaRepository<Order, Long> {

    @Query("select o from Order o order by o.id")
    Stream<Order> streamAll();
}

There is no @Transactional on the repository method—the transaction comes from the service that calls it. If you call streamAll() directly without a surrounding transaction, Hibernate opens and closes its own short session, and the stream will fail on the second read.

Consuming the stream

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.stream.Stream;

@Service
public class OrderExportService {

    private final OrderRepository orderRepository;

    public OrderExportService(OrderRepository orderRepository) {
        this.orderRepository = orderRepository;
    }

    @Transactional(readOnly = true)
    public void export(OrderWriter writer) {
        try (Stream<Order> orders = orderRepository.streamAll()) {
            orders.forEach(writer::write);
        }
    }
}

Five rules make this work:

  • Consume the stream inside the transaction. The connection stays open until the stream closes.
  • Close the stream with try-with-resources. An unclosed stream leaks the connection.
  • Never return the stream from a transactional method. The transaction closes when the method returns, and the caller iterates over a dead result set.
  • Never call collect() on it. That defeats the purpose.
  • Configure fetch size—otherwise the driver may still load the entire result set into memory.

The mistake: returning the stream

// Wrong: the transaction ends before the caller reads anything
@Transactional(readOnly = true)
public Stream<Order> streamOrders() {
    return orderRepository.streamAll();
}

When the method returns, Spring commits the transaction, closes the session, and releases the connection. The caller now holds a stream backed by a closed ResultSet, and iteration fails with StreamClosedException or IllegalStateException.

Configuring Fetch Size

Streaming behavior depends on the JDBC driver. Without a proper fetch size, the driver may load the entire result set into memory even though your code uses a Stream.

Per-query Hibernate hint

import org.hibernate.jpa.QueryHints;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.QueryHints;

import java.util.stream.Stream;

public interface OrderRepository extends JpaRepository<Order, Long> {

    @QueryHints(@jakarta.persistence.QueryHint(
            name = QueryHints.HINT_FETCH_SIZE,
            value = "500"))
    @Query("select o from Order o order by o.id")
    Stream<Order> streamAll();
}

Global setting

spring:
  jpa:
    properties:
      hibernate:
        jdbc:
          fetch_size: 500

Database-specific requirements

Database What streaming requires
PostgreSQL A positive fetch size and auto-commit off. With auto-commit on, the driver buffers the whole result set.
MySQL Either setFetchSize(Integer.MIN_VALUE) (legacy row-by-row streaming, cannot be combined with most cursors) or useCursorFetch=true in the URL with a positive fetch size (server-side cursor).
Oracle A positive fetch size. Oracle prefetches rows; it does not stream in the PostgreSQL sense, but the fetch size caps memory.
SQL Server TYPE_FORWARD_ONLY, CONCUR_READ_ONLY, and a positive fetch size.

Confirm behavior against your specific driver version. A hint that streams on PostgreSQL may not stream on MySQL without the cursor flag in the connection URL.

spring:
  datasource:
    url: "jdbc:mysql://localhost:3306/shop?useCursorFetch=true"

Transactions and Connection Lifetime

Streaming keeps a database connection checked out while rows are consumed. This is the single most important operational constraint.

The result set is tied to the connection. While the stream is being consumed, the connection cannot be returned to the pool. With a 20-connection Hikari pool:

spring:
  datasource:
    hikari:
      maximum-pool-size: 20

Twenty concurrent exports exhaust the pool, and every other request blocks on getConnection() until an export finishes.

Mitigation strategies:

  • Cap concurrent exports with a semaphore or dedicated executor.
  • Route exports through a separate connection pool.
  • Prefer keyset pagination when connections are scarce.
  • Enforce a maximum export duration.
  • Reject new exports when capacity is reached, rather than queueing them.

Cap concurrent exports

import org.springframework.stereotype.Service;

import java.util.concurrent.Semaphore;

@Service
public class ExportLimiter {

    private final Semaphore permits = new Semaphore(2);

    public boolean tryAcquire() {
        return permits.tryAcquire();
    }

    public void release() {
        permits.release();
    }
}
if (!exportLimiter.tryAcquire()) {
    throw new ExportCapacityExceededException(
            "Too many exports in progress. Try again later.");
}

try {
    exportService.export(writer);
} finally {
    exportLimiter.release();
}

For high-traffic systems, give exports a dedicated DataSource with its own pool. Exports then fail fast against their own capacity instead of starving the API.

Streaming to the HTTP Response

StreamingResponseBody lets Spring MVC write data progressively to the client without building the full response in memory. The body runs on a separate thread after the controller method returns—which is what makes the pattern work, because the request thread is released immediately.

Controller

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.io.IOException;

@RestController
public class OrderExportController {

    private final OrderExportService exportService;
    private final ObjectMapper objectMapper;

    public OrderExportController(OrderExportService exportService,
                                 ObjectMapper objectMapper) {
        this.exportService = exportService;
        this.objectMapper = objectMapper;
    }

    @GetMapping("/api/orders/export")
    public ResponseEntity<StreamingResponseBody> exportOrders() {
        StreamingResponseBody body = outputStream -> {
            try (JsonGenerator generator = objectMapper.getFactory()
                    .createGenerator(outputStream)) {

                generator.writeStartArray();
                exportService.export(order -> {
                    try {
                        generator.writeObject(order);
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                });
                generator.writeEndArray();
            }
        };

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=orders.json")
                .header(HttpHeaders.CONTENT_TYPE, "application/json")
                .body(body);
    }
}

The @Transactional(readOnly = true) on exportService.export() works as expected because Spring opens the transaction on the streaming thread. If the controller method itself were @Transactional, the transaction would close on the request thread before the streaming thread started—and the stream would fail.

The one limitation you can’t code around

Once the first byte is written, the HTTP status and headers are already sent. If an error occurs midway, you cannot return a clean JSON error response—you can only truncate the output. Clients receive valid-but-incomplete JSON, like [{"id":1},{"id":2},.

Two options:

  • Buffer the first N rows in memory before writing the first byte. If the export fails within that window, you can still return a proper 500.
  • Use a background job instead of a synchronous stream: generate the file, store it, return a download link when ready. Errors happen before the client ever sees a response.

For interactive exports where the response must stream, log the failure server-side and close the stream. The client can detect truncation from the missing closing ].

Streaming With Plain JDBC

Plain JDBC gives the most control over fetch size, result set type, and connection handling—and it avoids the Hibernate persistence context entirely.

import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@Service
public class JdbcOrderExportService {

    private final DataSource dataSource;

    public JdbcOrderExportService(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void export(OrderWriter writer) throws Exception {
        String sql = """
                select id, customer_id, total, status, created_at
                from orders
                order by id
                """;

        try (Connection connection = dataSource.getConnection()) {
            connection.setAutoCommit(false);

            try (PreparedStatement statement = connection.prepareStatement(
                    sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)) {

                statement.setFetchSize(500);

                try (ResultSet resultSet = statement.executeQuery()) {
                    while (resultSet.next()) {
                        writer.write(mapRow(resultSet));
                    }
                }
            }

            connection.commit();
        }
    }

    private OrderRow mapRow(ResultSet resultSet) throws Exception {
        return new OrderRow(
                resultSet.getLong("id"),
                resultSet.getLong("customer_id"),
                resultSet.getBigDecimal("total"),
                resultSet.getString("status"),
                resultSet.getTimestamp("created_at").toInstant()
        );
    }
}

Three reasons to prefer JDBC for large exports:

  • Explicit fetch size. No ambiguity about what the driver is doing.
  • No persistence context. Hibernate tracks every entity it loads, and managed entities pile up in memory even if you never touch them again.
  • Predictable memory. You allocate one row at a time, and the driver handles the cursor.

If you must stream entities through JPA, clear the persistence context periodically—not every row, which is expensive, but every n rows:

@PersistenceContext
private EntityManager entityManager;

int processed = 0;
while (iterator.hasNext()) {
    writer.write(iterator.next());
    if (++processed % 500 == 0) {
        entityManager.clear();
        entityManager.detach(/* keep any references you still need */);
    }
}

This keeps the persistence context small at the cost of detaching entities. If the export is genuinely large, plain JDBC or projection-based queries avoid the problem entirely.

Keyset Pagination: The Alternative

Keyset pagination avoids long-lived connections. It fetches batches using a stable key and returns the connection between batches:

import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface OrderRepository extends JpaRepository<Order, Long> {

    @Query("""
            select o from Order o
            where o.id > :lastId
            order by o.id
            """)
    List<Order> findNextBatch(@Param("lastId") Long lastId, Pageable pageable);
}
long lastId = 0;
int batchSize = 500;

while (true) {
    List<Order> batch = orderRepository.findNextBatch(
            lastId, PageRequest.of(0, batchSize));

    if (batch.isEmpty()) {
        break;
    }

    batch.forEach(writer::write);
    lastId = batch.get(batch.size() - 1).getId();
}

Advantages: connections are returned between batches, memory stays low, and an interrupted export can resume from the last ID.

Requirements: the sort key must be unique and indexed; rows shouldn’t change mid-export unless the export tolerates it; and the client must be able to wait for a long response or receive a generated file.

Do not use offset pagination (LIMIT … OFFSET …) for this pattern. The database scans and discards every row up to the offset, so page 10,000 is dramatically slower than page 1. Keyset pagination avoids that entirely because it uses an index range scan.

Monitoring and Limits

Exports need operational guardrails the rest of the app doesn’t.

Metrics to track: active exports, export duration (p50 / p95 / max), rows exported, bytes written, connection pool wait time, and failure/timeout rate.

Limits to enforce: maximum concurrent exports, maximum export duration, maximum rows per export, maximum response size, and per-user export quotas.

Timeout guard

import java.time.Duration;
import java.time.Instant;

Instant started = Instant.now();
Duration maxDuration = Duration.ofMinutes(5);

while (resultSet.next()) {
    if (Duration.between(started, Instant.now()).compareTo(maxDuration) > 0) {
        throw new ExportTimeoutException("Export exceeded time limit");
    }
    writer.write(mapRow(resultSet));
}

Check the timeout inside the row loop, not on a timer. A timer thread can’t safely close a ResultSet the loop is using. The cost of one Instant.now() per row is negligible compared to the cost of a hung connection.

Best Practices

  • Never load an unbounded result set into memory. If you can’t name the upper bound, you can’t load it.
  • Use read-only transactions for exports. They skip Hibernate’s dirty-checking and signal intent.
  • Configure fetch size for your driver. A Stream without a fetch size is not streaming.
  • Consume streams inside the transaction and close them with try-with-resources.
  • Bound concurrency. One export at a time per user, and a global cap you can defend with pool sizing.
  • Prefer keyset pagination over streaming when the connection pool is the bottleneck.
  • Use projections or plain JDBC to avoid persistence context growth.
  • Measure before you optimize. A 500-row fetch size is a reasonable default. The right number depends on row size, latency, and pool size—measure with realistic data.

Decision guide

Scenario Recommended approach
Small CSV or JSON export (under ~10k rows) Load and return
Large export, few concurrent users JPA stream or JDBC streaming
Large export, many concurrent users Keyset pagination or background job
Very large report (100M+ rows) Background job with file storage and a download link
Strict connection pool limits Keyset pagination with short transactions

FAQ

How do I stream a large database export in Spring Boot?

Return a Stream<T> from a repository method, consume it inside a @Transactional(readOnly = true) service, configure a fetch size for your driver, and write to a StreamingResponseBody.

Why does my JPA stream still use too much memory?

The driver is not streaming. Either the fetch size is missing, auto-commit is on, or the driver doesn’t support server-side cursors for your configuration. Check the driver requirements for your database above.

Why does my export exhaust the connection pool?

Streaming holds a connection open while rows are consumed. Cap concurrent exports, route them through a dedicated pool, or switch to keyset pagination.

Can I return a Stream from a Spring Data repository directly?

Yes, but the stream must be consumed inside the transaction that opened it. Returning it to a caller outside the transaction closes the result set before iteration.

What fetch size should I use?

Start at 500 and measure. The optimum depends on row size, network latency, and pool size. Smaller values reduce memory and round-trips; larger values reduce round-trips at the cost of buffering.

Is keyset pagination better than streaming?

For most production apps, yes—it returns connections between batches and survives failures. Use streaming when continuous output is required and connection capacity allows.

Can I stream CSV instead of JSON?

Yes. The same StreamingResponseBody pattern works with a CSV writer. Write rows incrementally, flush periodically, and set text/csv as the content type.

What happens if the client disconnects mid-export?

The next write to the output stream throws IOException. The try-with-resources blocks close the stream, the transaction rolls back, and the connection returns to the pool. Without try-with-resources, the connection leaks.

Final Thoughts

Streaming large database exports is less about writing fast and more about managing the scarce resource: the connection. JPA streams and plain JDBC give you continuous output at the cost of a held connection; keyset pagination trades continuous output for shorter, reusable connections. Pick based on your pool size and concurrency—not on which one looks simpler in a demo.

Whichever you choose: configure fetch size, bound concurrency, and monitor duration and pool health in production. The first OOM or pool-exhaustion incident will tell you which one you skipped.

Comments