Skip to content

Optimize implementation of Postgresql async notifications #270

Closed

Description

@franciscojunior

We were discussing async support in Npgsql in #121 (comment) and the issue of the real time notifications appeared.

@roji asked me to create another issue so we can discuss how we should handle it.

Other places where attempts to fix this problem appeared (for reference): #61 , #46 , #107

Activity

  1. Emill commented on Jul 16, 2014

    @Emill
    Contributor

    My idea:

    Use BeginRead with a zero length buffer as argument on the socket together with a callback. As @roji supposed in his async "proof of concept" code, that will wait until more data is available and then run the callback. In the callback, the notification message can be read and posted to the user's event handler. This event is preferably run on a new worker task in the thread pool, so the async callback can return immediately. Then a new BeginRead must be started again, to receive new notifications.

    When the user runs a query, we don't want to listen anymore for notifications, so abort the pending read operation using a CancellationToken. Some locking (or queuing) must also be added since the callback may at the moment be reading a notification message and this must be completed before we can continue. The case when the callback has just started but the reading of the notification message has not begun yet, and at the same time the user starts a query, must also be handled correctly. Since a notification message can be received any time, it must still be handled correctly while a query runs, while processing backend responses, as it does today.

    When the user's query has run and completed, a BeginRead must be started again, to receive new notifications. Using the "using" pattern with IDisposable, that can take care of stopping/restarting notifications, just like today. This works for the sync methods, but when async is later implemented, operations should preferably be queued if there is an ongoing reading of notification messages. Those operations should be run when the reading of the notification messages has completed, i.e. BeginGetReader or whatever should not block because we wait until the processing of notification messages has completed before returning.

    That way we won't allocate a thread that mostly does nothing.
    I think running the event on a separate worker thread is good because then Npgsql can continue its work whatever the user does in the event.

  2. roji commented on Jul 17, 2014

    @roji
    Member

    Thanks for all the really intelligent thoughts @Emill, it's really great to have you helping out on npgsql. Here are some comments on the above.

    I'd agree with your proposal, except that as far as I know, cancelling an async operation isn't possible before .NET 4. CancellationToken is something that's introduced along with Task, and the old Begin/End methods don't support anything resembling cancellation.

    However, that may not be a big problem. If we use a zero-length BeginRead, then it's no big deal if it continues even after the user starts a query. When the async notification callback is invoked, we can simply test the state of the connector. If it is currently handling a query, we do nothing, otherwise we read and fire the event. When the query completes we relaunch the zero-length BeginRead.

    One thing though... The zero-length read is something I haven't found serious documentation for, and having Begin/End reads like this interspersed with query code makes me uneasy. It may be safer to simply implement a single, global async notification thread which uses Select() to wait on all connections, and checks the state as described above to avoid interfering with queries. That would be a 100% safe way to implement this.

  3. Emill commented on Jul 17, 2014

    @Emill
    Contributor

    However, that may not be a big problem. If we use a zero-length BeginRead, then it's no big deal if it continues even after the user starts a query. When the async notification callback is invoked, we can simply test the state of the connector. If it is currently handling a query, we do nothing, otherwise we read and fire the event. When the query completes we relaunch the zero-length BeginRead.

    Yes, that is a good idea.

    I found http://int64.org/2009/05/15/tips-for-efficient-io/

    An undocumented feature of WSARecv is that you can request a 0-byte receive, which will complete when data has arrived. Then you can issue another WSARecv or use non-blocking I/O to pull out whatever is available. This lets us get notified when data can be received without actually locking memory.

    BeginRead internally uses WSARecv. I don't know his sources though.

    I also found http://stackoverflow.com/questions/4988168/wsarecv-and-wsabuf-questions which cites http://www.microsoft.com/mspress/books/sampchap/5726a.aspx#124 that is as a source from Microsoft.

    You post a zero byte read on all the connections and then post a real read when the zero byte read completes and you know that you have data available.

    Regarding

    It may be safer to simply implement a single, global async notification thread which uses Select() to wait on all connections, and checks the state as described above to avoid interfering with queries. That would be a 100% safe way to implement this.

    That will work for a small number of connections, but if there are 1000 connections, Select() must traverse all those 1000 connections, which might degrade performance. I don't know how serious this is though. That means when something happens on one connection, the Select must be restarted with all 1000 connections. As it is now, or with zero-read-async, only one listener must be set up.

  4. roji commented on Jul 17, 2014

    @roji
    Member

    @Emill, good points. I think Select() itself doesn't traverse all the connections (i.e. the actual implementation in the kernel is efficient), but it's true we'd have to manage the lists and traverse them in .NET.

    I think it's a matter of the what kind of load we expect to manage. If we don't expect async notifications all the time on a large number of connections (and I think that's the case), ReadAsync may be the more efficient choice. On the other hand, if not a lot of async notifications actually happen, then even the Select() overhead doesn't matter so much anymore... Plus there's the "unknown" matter of how safe it is to use the undocumented 0-length reads.

    I'd say we hold off with the implementation of this feature until the async work in #121 is complete, since the two have some interaction. Then we can make a decision between 0-length ReadAsync or Select()... Sounds good?

  5. Emill commented on Jul 17, 2014

    @Emill
    Contributor

    @Emill, good points. I think Select() itself doesn't traverse all the connections (i.e. the actual implementation in the kernel is efficient), but it's true we'd have to manage the lists and traverse them in .NET.

    Both mono and .NET traverses all connections.

    I think it's a matter of the what kind of load we expect to manage. If we don't expect async notifications all the time on a large number of connections (and I think that's the case), ReadAsync may be the more efficient choice. On the other hand, if not a lot of async notifications actually happen, then even the Select() overhead doesn't matter so much anymore... Plus there's the "unknown" matter of how safe it is to use the undocumented 0-length reads.

    Yes. The Select will return when there is data on any connection, not only async notifications. Also, it must be stopped and restarted during a query.

    I'd say we hold off with the implementation of this feature until the async work in #121 is complete, since the two have some interaction. Then we can make a decision between 0-length ReadAsync or Select()... Sounds good?

    Ok. Just remember to make the async code ready to whatever choice is made later ;)

  6. added this to the milestone on Aug 31, 2014
  7. self-assigned this
    on Aug 31, 2014
  8. changed the title [-]How to implement Npgsql realtime notifications aka sync notifications[/-] [+]Optimize implementation of Postgresql async notifications[/+] on Aug 31, 2014
  9. janslavsky commented on Oct 10, 2014

    @janslavsky

    Hello,

    I am using also mechanism of NOTIFY/LISTEN events from PostgreSQL DB. I facing this problem for more then 1,5 year. Is there any solution which I can test on my database? If there are multiple events fired sometimes takes a long time to receive them on client side.

    Thanks for help
    Jan

  10. roji commented on Oct 10, 2014

    @roji
    Member

    @janslavsky, there is no solution yet, but a lot of work that has gone into implementing async should help here. I'll probably be working on the notification optimization sometime soon, we definitely won't release 3.0 without it.

    But can you please describe exactly what problems you're encountering with the current implementation?

  11. janslavsky commented on Oct 13, 2014

    @janslavsky

    Hello roji,

    thanks for information. Here is description of my use-case. I am using trigger after update / insert on my table to fire notify events to subscribed clients where I want to handle that some IDs were inserted or updated. Clients are C# based application using npgsql version 2.1.1.0. I have a problem when I do a faster update of multiple entries in database - then events delivered to clients are delayed. Looks like npgsql is collecting them for some "unknown" time period and then sends them. Can I configure it somehow to fire events to clients one by one immediately? Basically I use this mechanism to avoid timers and in loops checking changes in some code tables. So I want to query DB just in time when it is really necessary - something was changed or inserted - then I am caching just modified or newly inserted data.

    Thanks for your support.

  12. 23 remaining items

  13. roji commented on Dec 5, 2014

    @roji
    Member

    @akontsevich, that seems to make sense, I'm pretty sure it's a usage issue on your side and not an Npgsql bug.

    First, if you don't open a connection for every log record, I think that means you're using the same database connection from two concurrent threads. The moment two log records happen to be emitted at the same time - boom.

    You should definitely open a connection for every log record, and have connection pooling on (the default) - this means you don't really connect. I don't know about your particular log setup, but you should definitely concentrate on the second error - executing a command on a closed connection. Make sure connection pooling isn't turned off in your connection string (the Pooling parameter should not be set to false).

  14. drusellers commented on Jan 15, 2015

    @drusellers

    Looking forward to this support. :)

  15. roji commented on Jan 21, 2015

    @roji
    Member

    Note @Emill's comment in #453 about DataAvailable not working reliably with Microsoft SslStream

  16. roji commented on Mar 29, 2015

    @roji
    Member

    @Emill, don't forget we still need to find a solution for SemaphoreSlim which is only available in .NET 4.5

  17. modified the milestones: , 3.0-beta1 on Mar 30, 2015
  18. roji commented on May 24, 2015

    @roji
    Member

    Closing this as all the work has been done and we're probably going to support .NET 4.5 only

  19. drusellers commented on May 24, 2015

    @drusellers

    DOPE

  20. modified the milestones: 3.0-beta1, on Aug 7, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions