You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Optimize implementation of Postgresql async notifications #270
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.
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.
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.
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.
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.
@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?
@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 ;)
changed the title [-]How to implement Npgsql realtime notifications aka sync notifications[/-][+]Optimize implementation of Postgresql async notifications[/+]on Aug 31, 2014
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.
@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?
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.
@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).
Activity
Emill commentedon Jul 16, 2014
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.
roji commentedon Jul 17, 2014
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.
Emill commentedon Jul 17, 2014
Yes, that is a good idea.
I found http://int64.org/2009/05/15/tips-for-efficient-io/
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.
Regarding
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.
roji commentedon Jul 17, 2014
@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?
Emill commentedon Jul 17, 2014
Both mono and .NET traverses all connections.
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.
Ok. Just remember to make the async code ready to whatever choice is made later ;)
[-]How to implement Npgsql realtime notifications aka sync notifications[/-][+]Optimize implementation of Postgresql async notifications[/+]janslavsky commentedon Oct 10, 2014
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
roji commentedon Oct 10, 2014
@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?
janslavsky commentedon Oct 13, 2014
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.
23 remaining items
roji commentedon Dec 5, 2014
@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).
drusellers commentedon Jan 15, 2015
Looking forward to this support. :)
roji commentedon Jan 21, 2015
Note @Emill's comment in #453 about DataAvailable not working reliably with Microsoft SslStream
roji commentedon Mar 29, 2015
@Emill, don't forget we still need to find a solution for SemaphoreSlim which is only available in .NET 4.5
roji commentedon May 24, 2015
Closing this as all the work has been done and we're probably going to support .NET 4.5 only
drusellers commentedon May 24, 2015
DOPE