title: Streaming file from S3 directly to response
body: <p>I have following code that acts as a gateway to S3 bucket. The purpose of this is to download files located on S3 but without exposing S3 item links.
  All works ok but after about 50 downloads, we keep getting <code>Timeout waiting for connection from pool</code> exceptions.
  I found that this might be caused by not closing the <code>s3Object.getObjectContent()</code> but as you can see I'm using "try with resources" which ensures that <code>close()</code> is invoked. Not only I'm doing this on the stream but also on the object itself. This is kind of a last resort as it doesn't change anything. In fact S3Object.close() does the same thing - closes the underlying InputStream.</p>
  
  <p>When I test this manually, I can see that the <code>close()</code> is being invoked.</p>
  
  <pre><code>@GET
  @Produces({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON})
  @Path("/{id}/download")
  
  public Response download(@NotNull @PathParam("id") String id) {
      return repository.get()
          .map(record -&gt; Response.status(OK)
              .header(HttpHeaders.CONTENT_DISPOSITION, "...")
              .entity((StreamingOutput) outputStream -&gt; {
                  try (S3Object s3Object = s3Service.getObject(record.getS3Key());
                      InputStream inputStream = s3Object.getObjectContent()) {
  
                      byte[] buffer = new byte[1024];
                      int bytesRead;
                      while ((bytesRead = inputStream.read(buffer)) != -1) {
                          outputStream.write(buffer, 0, bytesRead);
                          outputStream.flush();
                      }
                      outputStream.flush();
                  }
              })
              .build())
          .orElseThrow(() -&gt; new EntityNotFoundException(String.format("Could not find download id: %s", id)));
  }
  </code></pre>
  
  <p>[EDIT]</p>
  
  <ul>
  <li>AWS S3 java lib version 1.11.308</li>
  <li>the AmazonS3 is set up as a singleton</li>
  </ul>