<?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 Santiago Londono on Medium]]></title>
        <description><![CDATA[Stories by Santiago Londono on Medium]]></description>
        <link>https://medium.com/@santiago.londono_45964?source=rss-db95191c5349------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*oyqdXCu-wThaylfW</url>
            <title>Stories by Santiago Londono on Medium</title>
            <link>https://medium.com/@santiago.londono_45964?source=rss-db95191c5349------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 00:48:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@santiago.londono_45964/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[Deja de cargar archivos S3 en memoria: streaming real con Spring WebFlux]]></title>
            <link>https://medium.com/somos-pragma/deja-de-cargar-archivos-s3-en-memoria-streaming-real-con-spring-webflux-4874898f259e?source=rss-db95191c5349------2</link>
            <guid isPermaLink="false">https://medium.com/p/4874898f259e</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[java17]]></category>
            <category><![CDATA[spring-webflux]]></category>
            <category><![CDATA[aws-sdk]]></category>
            <dc:creator><![CDATA[Santiago Londono]]></dc:creator>
            <pubDate>Tue, 17 Mar 2026 03:42:06 GMT</pubDate>
            <atom:updated>2026-03-17T20:01:13.453Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Vu0rPvSzgVVg5TUKviz1mQ.png" /></figure><p>¿El problema? Tienes un microservicio que necesita procesar un archivo CSV almacenado en S3. El archivo puede tener cientos de miles (o incluso millones) de registros. La primera implementación que se te ocurre (y la que probablemente ya tienes) se ve así:</p><pre>s3AsyncClient.getObject(<br>    GetObjectRequest.builder().bucket(bucket).key(key).build(),<br>    AsyncResponseTransformer.toBytes()<br>)</pre><p>AsyncResponseTransformer.toBytes() descarga <strong>todo el objeto S3 completo en un byte[] del heap</strong> antes de que puedas leer la primera línea. Para un CSV de cinco millones de registros, eso puede significar fácilmente 500 MB o más en memoria de forma simultánea.</p><p>El resultado: OutOfMemoryError en producción, GC bajo presión constante, tiempos de arranque que escalan con el tamaño del archivo y cero posibilidad de hacer <em>backpressure</em> real.</p><p>En este tutorial veremos cómo resolverlo usando AsyncResponseTransformer.toPublisher() junto con un PipedInputStream/PipedOutputStream para obtener un<em> streaming</em> verdadero desde S3, sin cargar el archivo completo en memoria.</p><h3>Requisitos previos</h3><ul><li>Spring Boot 3.x con Project Reactor (WebFlux o solo reactor-core).</li><li>AWS SDK for Java v2 (software.amazon.awssdk:s3).</li><li>Java 17+.</li></ul><p>Dependencias en build.gradle:</p><pre>// BOM para gestionar versiones del SDK de AWS<br>implementation platform(&#39;software.amazon.awssdk:bom:2.25.35&#39;)<br>implementation &#39;software.amazon.awssdk:s3&#39;<br><br>// Reactor (incluido con Spring Boot WebFlux)<br>implementation &#39;org.springframework.boot:spring-boot-starter-webflux&#39;</pre><h3>El enfoque naive y sus problemas</h3><p>Antes de ver la solución, entendamos exactamente qué hace el código típico:</p><pre>// Enfoque naive<br>public Mono&lt;InputStream&gt; getObject(String bucket, String key) {<br>    return Mono.fromFuture(<br>        s3AsyncClient.getObject(<br>            GetObjectRequest.builder().bucket(bucket).key(key).build(),<br>            AsyncResponseTransformer.toBytes()<br>        )<br>    ).map(ResponseBytes::asInputStream);<br>}</pre><p><strong>¿Qué pasa por dentro?</strong></p><ol><li>El SDK de AWS abre una conexión HTTP con S3.</li><li>Descarga <strong>todos</strong> los bytes del objeto y los almacena en un byte[].</li><li>Solo cuando el <em>download</em> termina al 100%, el CompletableFuture se completa.</li><li>Recién ahí te entrega el InputStream que apunta a bytes ya en memoria.</li></ol><p>Para archivos pequeños esto es transparente. Para archivos grandes es un desastre.</p><pre>S3 --(descarga completa)--&gt; byte[] en heap --&gt; InputStream --&gt; tu código<br>        |<br>   TODO el archivo<br>   está aquí antes<br>   de leer la primera línea</pre><p><strong>La solución:</strong> streaming real con toPublisher()</p><p>AWS SDK v2 ofrece AsyncResponseTransformer.toPublisher(), que en vez de esperar a tener todos los bytes, te entrega un SdkPublisher&lt;ByteBuffer&gt;, un <em>stream</em> reactivo que emite <em>chunks</em> de bytes a medida que llegan por la red.</p><p>El reto: tus parsers CSV probablemente usan BufferedReader.readLine(), que es una API bloqueante. Necesitas un puente entre el mundo reactivo del SDK y el mundo bloqueante de tu lector CSV.</p><p>La solución es un <strong><em>pipe</em> bidireccional</strong> entre dos <em>threads:</em></p><pre>S3 (red)<br>  |<br>  |  toPublisher() -&gt; SdkPublisher&lt;ByteBuffer&gt;<br>  |  (chunks llegan a medida que la red los entrega)<br>  V<br>Flux&lt;ByteBuffer&gt;<br>  |  publishOn(Schedulers.boundedElastic())<br>  V<br>[Thread A — escritor]<br>  |  PipedOutputStream.write(bytes)<br>  |       &lt;-&gt; buffer 64 KB<br>  |  PipedInputStream.read()<br>  V<br>[Thread B — lector]<br>  |  BufferedReader.readLine()<br>  V<br>  Tu lógica de negocio (parser CSV, validaciones, etc.)</pre><p>El <em>pipe</em> actúa como <em>buffer</em> (64 KB por defecto). Si el lector no consume rápido, la escritura se bloquea naturalmente activando TCP flow control hacia S3, lo que reduce la velocidad de envío. <strong>Es <em>backpressure</em> real, sin acumular datos en RAM.</strong></p><h3>Implementación paso a paso</h3><p><strong>Paso 1: Configurar S3AsyncClient</strong></p><pre>@Configuration<br>public class S3Config {<br><br>    @Bean<br>    public S3AsyncClient s3AsyncClient(<br>            @Value(&quot;${aws.region}&quot;) String region,<br>            @Value(&quot;${aws.s3.endpoint}&quot;) String endpoint) {<br><br>        return S3AsyncClient.builder()<br>                .region(Region.of(region))<br>                .endpointOverride(URI.create(endpoint))<br>                .build();<br>    }<br>}</pre><p><strong>Paso 2: La operación de <em>streaming </em>en S3Operations</strong></p><p>Este es el cambio central. Reemplazamos toBytes() por toPublisher() y conectamos el resultado a un <em>pipe</em>:</p><pre>@Component<br>@RequiredArgsConstructor<br>public class S3Operations {<br><br>    private final S3AsyncClient s3AsyncClient;<br><br>    public Mono&lt;InputStream&gt; getObject(String bucketName, String objectKey) {<br>        return Mono.fromFuture(<br>                s3AsyncClient.getObject(<br>                    GetObjectRequest.builder()<br>                        .key(objectKey)<br>                        .bucket(bucketName)<br>                        .build(),<br>                    AsyncResponseTransformer.toPublisher())) // streaming, no bytes<br>                .flatMap(publisher -&gt; {<br>                    try {<br>                        // Pipe con buffer de 64 KB<br>                        PipedOutputStream out = new PipedOutputStream();<br>                        PipedInputStream in = new PipedInputStream(out, 65536);<br><br>                        // Thread A: escribe chunks del SDK en el pipe<br>                        Flux.from(publisher)<br>                            .publishOn(Schedulers.boundedElastic())<br>                            .subscribe(<br>                                buf -&gt; {<br>                                    try {<br>                                        byte[] bytes = new byte[buf.remaining()];<br>                                        buf.get(bytes);<br>                                        out.write(bytes);<br>                                    } catch (IOException e) {<br>                                        throw new UncheckedIOException(e);<br>                                    }<br>                                },<br>                                err -&gt; {<br>                                    try { out.close(); } catch (IOException ignored) {}<br>                                },<br>                                () -&gt; {<br>                                    try { out.close(); } catch (IOException ignored) {}<br>                                }<br>                            );<br><br>                        // Se emite inmediatamente — Thread B puede comenzar a leer<br>                        return Mono.just((InputStream) in);<br>                    } catch (IOException e) {<br>                        return Mono.error(e);<br>                    }<br>                });<br>    }<br>}</pre><p><strong>¿Por qué publishOn(Schedulers.boundedElastic()) y no subscribeOn?</strong></p><ul><li>publishOn redirige los <strong><em>callbacks </em>del suscriptor</strong> (onNext, onError, onComplete) al <em>scheduler</em> indicado. Como esos <em>callbacks </em>hacen out.write(bytes) (bloqueante cuando el <em>pipe</em> está lleno), necesitan correr en un <em>thread</em> de I/O, no en el <em>event loop</em> de Netty.</li><li>boundedElastic es el <em>scheduler</em> de Reactor diseñado para esto: maneja <em>threads </em>bloqueantes, crece bajo demanda y no bloquea el <em>event loop</em> principal.</li></ul><p><strong>Paso 3: El <em>adapter</em> que expone el <em>streaming</em> al dominio</strong></p><pre>@Repository<br>@AllArgsConstructor<br>public class S3Adapter implements FileRepository {<br><br>    private final S3Operations s3Operations;<br>    private final S3Properties properties;<br><br>    @Override<br>    public Mono&lt;InputStream&gt; getFileByKey(String key) {<br>        return Mono.defer(() -&gt; s3Operations.getObject(properties.getBucketName(), key)<br>                .onErrorMap(<br>                    ex -&gt; !(ex instanceof BusinessException),<br>                    ex -&gt; new TechnicalException(&quot;Error leyendo archivo de S3&quot;, ex)<br>                )<br>        );<br>    }<br>}</pre><p><strong>Paso 4: El parser CSV que consume el InputStream</strong></p><p>Con el <em>streaming</em> implementado en la capa de infraestructura, el parser del dominio no necesita saber nada sobre S3 ni sobre Reactor. Solo recibe un InputStream.</p><p><strong>El cambio clave aquí es subscribeOn(Schedulers.boundedElastic())</strong>, que garantiza que las llamadas bloqueantes a readLine() no ocurran en el <em>event loop </em>de Netty:</p><pre>@Component<br>public class CsvFileParser {<br><br>    public Mono&lt;ParsedBatch&gt; parse(InputStream stream, String fileName) {<br>        return Mono.fromCallable(() -&gt; {<br><br>            // BufferedReader sobre el PipedInputStream: lee a medida que llegan los bytes<br>            try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {<br><br>                String headerLine = reader.readLine(); // lee cabecera<br>                validateHeader(headerLine);<br><br>                List&lt;Record&gt; records = new ArrayList&lt;&gt;();<br>                String line;<br>                int count = 0;<br><br>                while ((line = reader.readLine()) != null) {<br>                    line = line.trim();<br>                    if (!line.isEmpty()) {<br>                        records.add(parseLine(line));<br>                        count++;<br>                    }<br>                }<br><br>                return new ParsedBatch(fileName, records);<br><br>            } catch (IOException e) {<br>                throw new TechnicalException(&quot;Error leyendo CSV&quot;, e);<br>            }<br><br>        }).subscribeOn(Schedulers.boundedElastic()); // obligatorio<br>    }<br>}</pre><p><strong>¿Por qué subscribeOn aquí?</strong></p><p>Con toPublisher(), el InputStream no tiene los bytes precargados. Cada readLine() puede <strong>bloquear</strong> esperando que el <em>thread </em>A escriba más datos en el <em>pipe.</em> Si ese bloqueo ocurriera en un <em>thread</em> de Netty, paralizaría el cliente HTTP. subscribeOn(Schedulers.boundedElastic()) mueve toda la ejecución del Mono.fromCallable a un <em>thread</em> del <em>pool </em>de I/O.</p><p><strong>Paso 5: Orquestar el flujo completo</strong></p><pre>@Service<br>@RequiredArgsConstructor<br>public class ProcessFileUseCase {<br><br>    private final FileRepository fileRepository;<br>    private final CsvFileParser parser;<br><br>    public Mono&lt;Void&gt; process(String s3Key) {<br>        return fileRepository.getFileByKey(s3Key)        // Mono&lt;InputStream&gt;<br>                .flatMap(stream -&gt; parser.parse(stream, s3Key))  // Mono&lt;ParsedBatch&gt;<br>                .flatMap(this::executeBusinessLogic)<br>                .then();<br>    }<br><br>    private Mono&lt;Void&gt; executeBusinessLogic(ParsedBatch batch) {<br>        // tu lógica aquí<br>        return Mono.empty();<br>    }<br>}</pre><p><strong>Ciclo de vida completo</strong></p><p>Veamos qué ocurre cuando se suscribe al <em>pipeline</em>:</p><pre>1. fileRepository.getFileByKey(&quot;input.csv&quot;)<br>   └─ S3AsyncClient.getObject(request, toPublisher())<br>      └─ CompletableFuture se completa al recibir CABECERAS HTTP (no el cuerpo)<br>         └─ Mono emite el SdkPublisher&lt;ByteBuffer&gt;<br>            └─ flatMap: se crea PipedOutputStream/PipedInputStream<br>               └─ Flux.from(publisher).publishOn(boundedElastic).subscribe(...)<br>                  Thread A queda listo para recibir bytes de la red<br>               └─ Mono.just(pipedInputStream) emitido INMEDIATAMENTE<br><br>2. parser.parse(pipedInputStream, &quot;input.csv&quot;)<br>   subscribeOn(boundedElastic) -&gt; Thread B inicia<br>   └─ BufferedReader.readLine() bloquea esperando datos<br>      Thread A recibe primer ByteBuffer de S3 -&gt; escribe en PipedOutputStream<br>      Thread B desbloquea -&gt; procesa la línea<br>      ... (ciclo continúa) ...<br>      Thread A recibe último ByteBuffer -&gt; cierra PipedOutputStream<br>      Thread B recibe EOF en readLine() -&gt; sale del while<br>      └─ Mono emite ParsedBatch<br><br>3. executeBusinessLogic(batch)<br>   └─ lógica de negocio con los registros ya en memoria</pre><h3>Comportamiento ante errores</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1pQlHkPoE29j8S69gqPE0w.png" /></figure><h3>Prueba unitaria del streaming</h3><p>Para probar el componente S3Operations, la clave es que el <em>mock</em> del S3AsyncClient devuelva un ResponsePublisher real (no un ResponseBytes):</p><pre>@Test<br>void shouldStreamFileFromS3() {<br>    // Construimos un SdkPublisher&lt;ByteBuffer&gt; real con datos de prueba<br>    byte[] csvContent = &quot;col1,col2\nvalue1,value2\n&quot;.getBytes(StandardCharsets.UTF_8);<br>    SdkPublisher&lt;ByteBuffer&gt; sdkPublisher =<br>            SdkPublisher.adapt(Flux.just(ByteBuffer.wrap(csvContent)));<br><br>    ResponsePublisher&lt;GetObjectResponse&gt; responsePublisher =<br>            new ResponsePublisher&lt;&gt;(GetObjectResponse.builder().build(), sdkPublisher);<br><br>    given(s3AsyncClient.getObject(<br>            any(GetObjectRequest.class),<br>            any(AsyncResponseTransformer.class)))<br>        .willReturn(CompletableFuture.completedFuture(responsePublisher));<br><br>    // Verificamos que se emite el InputStream<br>    StepVerifier.create(s3Operations.getObject(&quot;my-bucket&quot;, &quot;input.csv&quot;))<br>            .expectNextCount(1)<br>            .verifyComplete();<br>}<br><br>@Test<br>void shouldPropagateS3ErrorAsTechnicalException() {<br>    given(s3AsyncClient.getObject(<br>            any(GetObjectRequest.class),<br>            any(AsyncResponseTransformer.class)))<br>        .willReturn(CompletableFuture.failedFuture(<br>                SdkException.create(&quot;Connection refused&quot;, new RuntimeException())));<br><br>    StepVerifier.create(s3Adapter.getFileByKey(&quot;input.csv&quot;))<br>            .expectError(TechnicalException.class)<br>            .verify();<br>}</pre><h3>¿Cuándo NO usar este enfoque?</h3><ul><li><strong>Archivos pequeños (&lt; 1 MB):</strong> el <em>overhead</em> del <em>pipe</em> no vale la pena. toBytes() es más simple y suficientemente rápido.</li><li><strong>Procesamiento <em>stateless</em> fila por fila:</strong> si puedes procesar cada registro de forma independiente sin necesitar el <em>batch</em> completo, considera un enfoque Flux&lt;Record&gt; con flatMap y concurrencia controlada.</li><li><strong>Necesitas reintento por registro fallido:</strong> con este enfoque el archivo ya fue “consumido”. Para reintentos granulares se recomienda escribir primero a un destino intermedio (DynamoDB, cola SQS) durante la lectura.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R8xB3f4jgNS7u0mRd4RoJA.png" /></figure><p>Con solo dos cambios toPublisher() en la capa de infraestructura y subscribeOn(Schedulers.boundedElastic()) en el parser, pasas de cargar el archivo completo en memoria a un <em>pipeline</em> de <em>streaming </em>real que escala con cualquier tamaño de archivo.</p><p><strong>Fuentes:</strong></p><p><strong>AWS SDK for Java v2</strong></p><p>AsyncResponseTransformer (toPublisher, toBytes) — Javadoc oficial <a href="https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/core/async/AsyncResponseTransformer.html">https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/core/async/AsyncResponseTransformer.html</a></p><p>SdkPublisher y su método adapt() — Javadoc oficial <a href="https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/core/async/SdkPublisher.html">https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/core/async/SdkPublisher.html</a></p><p>ResponsePublisher — Javadoc oficial <a href="https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/core/async/ResponsePublisher.html">https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/core/async/ResponsePublisher.html</a></p><p>S3AsyncClient — getObject — Javadoc oficial <a href="https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3AsyncClient.html#getObject(software.amazon.awssdk.services.s3.model.GetObjectRequest,software.amazon.awssdk.core.async.AsyncResponseTransformer)">https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3AsyncClient.html<em>#getObject(software.amazon.awssdk.services.s3.model.GetObjectRequest,software.amazon.awssdk.core.async.AsyncResponseTransformer)</em></a></p><p>Developer Guide — Async operations con S3 <a href="https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/asynchronous.html">https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/asynchronous.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4874898f259e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/somos-pragma/deja-de-cargar-archivos-s3-en-memoria-streaming-real-con-spring-webflux-4874898f259e">Deja de cargar archivos S3 en memoria: streaming real con Spring WebFlux</a> was originally published in <a href="https://medium.com/somos-pragma">Pragma</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>