Skip to content

Send multiple emails per session connection #198

Closed

Description

@petarov

Hi! This is more of a question rather than an issue.

I'm working on an implementation that has to send many emails using one and the same SMTP server. I saw that async sending is already supported which is pretty cool! However, I was looking for a way to send many emails synchronously over an already established TCP connection.

Browsing the MailSender code I stumbled on this part. I think this opens a new connection for each email, right? Does it make sense to improve this, so that it reuses the transport/session to send several messages synchronously?

Activity

  1. bbottema commented on Mar 29, 2019

    @bbottema
    Owner

    Hi @petarov, it could be an improvement, but I'm unaware of any performance issues with creating new connections for emails. Do you have experience with sending emails in bulk such that reusing a connection shows better results? Or is there another reason you wish to reuse a connection?

  2. petarov commented on Mar 31, 2019

    @petarov
    Author

    Thanks for the feedback @bbottema! I'd like to reuse the connection so that that same underlying tcp socket gets used for sending bulk (hundreds to thousands of emails) of data. I'm generally trying to squeeze as much performance as possible for a product I'm working on.

    That being said, I don't have any data to compare the performance at the moment, but I'll try to prepare some and come back to you with numbers for a better overview.

  3. bbottema commented on Apr 1, 2019

    @bbottema
    Owner

    Thanks, it would be very helpful to have some more data. Generally speaking as a rule of thumb I'm very cautious of premature optimization, since that makes the code more complex often without really needing it. But if a real case can be made I'm all for it.

  4. petarov commented on Apr 5, 2019

    @petarov
    Author

    Ok, here are a bunch of, let's call them naïve, tests using SimpleJavaMail and just plain JavaMail with Transport.sendMessage(). I've used FakeSMTP as an SMTP server to perform the tests. Test email size = 15Kb.

    It can be observed in the SMTP protocol handshake that the JavaMail+sendMessage variant does not close the connection, but rather keeps sending emails after EHLO was initially sent. The results from my tests are below. The client code's running on a macOS machine and the SMTP server on a remote Linux server.

    The elapsed time results as mean values are irrelevant, but the difference does seem to be around 2x in favour of JavaMail+sendMessage.

    Method Emails Count Elapsed Time
    SimpleJavaMail 100 40,71 seconds
    JavaMail+sendMessage 100 21,11 seconds
    SimpleJavaMail 1000 404.71 seconds (6m 45s)
    JavaMail+sendMessage 1000 198.70 seconds (3m 18s)
    SimpleJavaMail 10,000 3921,03 seconds (1h 5m 22s)
    JavaMail+sendMessage 10,000 1954,81 seconds (32m 35s)

    Of course, I might have missed something, so here's the repo, if you'd like to take a look. (Warning! Code's messy.)

    And finally, I actually think that 2x is not that much of an issue for my use case (~500 max), so this issue could be closed. I can live with SimpleJavaMail working as it is at the moment. 😉

  5. bbottema commented on Apr 5, 2019

    @bbottema
    Owner

    Can you please add a third approach of JavaMail sendMessage without reusing the connection? I'm curious to know how much overhead Simple Java Mail adds.

  6. petarov commented on Apr 6, 2019

    @petarov
    Author

    Sure, so I tested 5 variants.

    Variant 1 - SimpleJavaMail. (Default Mailer, no threading parameters.)
    Variant 2 - SimpleJavaMail with 10 threads. Async send.
    Variant 3 - Transport.send()

    Transport.send(msg);

    Variant 4 - Transport+getInstance()+connect()+sendMessage().

            try (Transport t = session.getTransport()) {
                t.connect();
                t.sendMessage(msg, msg.getAllRecipients());
            } finally {
                // do nothing
            }

    Variant 5 - transportInstance.sendMessage(). Same as JavaMail+sendMessage in my tests above. Transport instance is created once and it's used for each email being sent.

            if (!transport.isConnected())
                transport.connect();
            transport.sendMessage(msg, msg.getAllRecipients());

    Results

    # Method Emails Count Elapsed Time
    1 SimpleJavaMail 100 38,64 seconds
    2 SimpleJavaMail+10 Threads 100 0,14 seconds
    3 Transport.send() 100 38,16 seconds
    4 Transport+getInstance()+connect()+sendMessage() 100 38,79 seconds
    5 transportInstance.sendMessage() 100 19,22 seconds

    No doubt, SimpleJavaMail + threads is the fastest variant, if threading is desired. 😎

    Last edit, maybe it's worth adding that Variant 5 should be used with caution in multi-threaded scenarios as stated in this stackoverflow comment.

  7. bbottema commented on Apr 6, 2019

    @bbottema
    Owner

    Excellent work, thank you!

    In conclusion, Simple Java Mail performance is pretty good in parallel mode, but can be improved even further roughly increasing performance by a factor of two when reusing Transport connections from a pool.

    Interesting though that establishing a connection to the smtp server takes about the same time as actually sending an email to it!

    I'll leave this open after all as a low-priority enhancement. Thanks again!

  8. added this to the 6.0.1 milestone on Apr 6, 2019
  9. 27 remaining items

  10. bbottema commented on Jan 26, 2020

    @bbottema
    Owner

    Unless this is a bug, this can only occur if the pool was shut down and then reused. On shut down, the connection pools are discarded, but the cluster key remains. If you then try to reuse the cluster key, this exception is thrown.

    Is it possible, you are shutting down the connection pool on this line, before the threads are done sending? That would explain the 0,12 seconds ;)

  11. petarov commented on Jan 26, 2020

    @petarov
    Author

    Yeah, that was a bummer. The test did not wait on the AsyncResponse futures to complete. It seems my older tests were also compromised by this. I totally overlooked it.

    It looks much more realistic now at 4,47 sec. I've updated the table above. 😉

    Still, I'm unsure when/how to call mailer.shutdownConnectionPool(). If I invoke mailer.shutdownConnectionPool().get() when all messages get sent, it just seems to block indefinitely. Any advice on that?

  12. bbottema commented on Jan 27, 2020

    @bbottema
    Owner

    Seeing your code, I can imagine two methods for shutting down:

    • The current one that waits for shutdown or times out with exception
    • A new one that waits for shutdown or forces a shutdown after a timeout

    Regarding your question on how to use the current one: if your threads are done, it should definitely not block indefinitely. That would be a bug.

    One possibility is that, while sending an email in a thread, if it fails then the claimed Transport is not released back into the pool. In this scenario the pool blocks indefinitely because it waits for all resources to free up. Did you verify all mails sent without issue?

    Though that might also be considered a bug if a transport is not released if the email was met with an exception (although releasing it back to the pool might mean the pool is now poisoned with a broken resource). Hmm, food for thought.

  13. petarov commented on Jan 28, 2020

    @petarov
    Author

    Did you verify all mails sent without issue?

    Yep, they are all being sent successfully. I did a simple 10 emails tests. All received and no exception was reported by AsyncResponse.onException(). I could see all 10 at the SMTP server side as well.

    Interestingly enough, if I just create a new mailer and invoke mailer.shutdownConnectionPool().get() without sending any Emails, it also blocks indefinitely. 🤔

  14. bbottema commented on Jan 30, 2020

    @bbottema
    Owner

    Yep it's a bug. The combined Futures of all pools being shutdown are aggregated into a FutureTask which itself is never run (the pools do shutdown, but the future task doesn't perform the wait closure) so it never completes and hence .get() blocks indefinitely. Whoops.

  15. bbottema commented on Jan 31, 2020

    @bbottema
    Owner

    Actually were are a bunch of issues where executor services were not shut down properly, the aggregate pools shutdown future task not executing (and implemented wrong).

    I've fixed all these issues under #246.

  16. bbottema commented on Feb 1, 2020

    @bbottema
    Owner

    6.0.2 released, all shutting down issues should be gone now!

  17. bbottema commented on Feb 1, 2020

    @bbottema
    Owner

    @petarov With that out of the way, could you please add a test with both multiple threads and a connection pool? The best would be to run a warmup cycle first and then perform all tests at once so they are guaranteed to run under same parameters.

    Also if you would post the system details (cpu, memory etc.) of both the client and server system that would be a great help. This would give a more complete frame of reference and I'll include it on the website as a rough reference performance (awesome!). If you're ok with having this data published that is.

  18. petarov commented on Feb 3, 2020

    @petarov
    Author

    Ok, it all looks good in 6.0.2 so far.

    Here's the input you requested, but I'm not sure if this is something to put on the website. I expect the results will definitely very when using a real SMTP server. It's your call. 😉

    Test Parameters

    • simplejavamail 6.0.2
    • javax.mail 1.6.2
    • 100 emails sent to a remote SMTP server with average ping ~50 ms.
    • Client - macOS Catalina, 8 CPU, 16 GB RAM, AdoptOpenJDK 11. Java VM was warmed up.
    • Server - CentOS Linux, 6 CPU, 12 GB RAM, OpenJDK 1.8, FakeSMTP as server*

    Results

    Test Emails Count # 1 # 2 # 3 Average Elapsed Time
    ThreadPoolSize=10 + CPool MaxSize=4 100 4.41 4.56 4.71 4.56 sec.
    ThreadPoolSize=10 + CPool MaxSize=1 100 14.86 14.61 14.58 14.68 sec.
    ThreadPoolSize=0 + CPool MaxSize=4 100 16.64 16.50 16.91 16.68 sec.
    JavaMail Transport 100 19.60 18.82 19.93 19.45 sec.
    • Both threaded and connection pool tests were done with the default values in the MailerRegularBuilderImpl builder. No customizations of the thread pool or connection pool sizes.

    • FakeSMTP ran in memory mode, no mails were saved on disk, using java -jar fakeSMTP-2.0.jar -m -s -b -p <port>

  19. bbottema commented on Feb 3, 2020

    @bbottema
    Owner

    Thanks a lot for your effort! Maybe I'm misunderstanding though, because I still miss a test with both multiple threads and a connection pool (as a combo).

    Additionally, I don't suppose it's easy for you to set up another server (or two) to run as a cluster? I wonder if we can get those 100 emails down to a single second 😏

  20. petarov commented on Feb 17, 2020

    @petarov
    Author

    Just did an update of my comment above. TBH, I'm a bit unsure of the exact specifics of how the threads and connection pools are working together, but the performance does seem to improve as I increase the number of threads and connection pool max size. So, it is more or less what I would have expected.

    A cluster run would be a challenge. Can't promise anything, but perhaps if time permits.

  21. bbottema commented on Feb 17, 2020

    @bbottema
    Owner

    Yeah, don't feel pressured at all, you did so much already.

  22. bbottema commented on May 3, 2020

    @bbottema
    Owner

    So we ran into this bug, which I think makes all your tests invalid? (crap)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions