Skip to content

pubsub :: async_receive2 hangs forever in sentinel mode #435

Open

Description

@madkote

hi,
in sentinel mode, the connection is normally recovered for async_exec() . But not for async_receive2.

is there a plan to add the recovery with auto subscribe?

Activity

  1. anarthal commented on Jul 27, 2026

    @anarthal
    Collaborator

    If it's not recovered, this is a bug on our side. Thanks for reporting. I will investigate.

  2. anarthal commented on Jul 27, 2026

    @anarthal
    Collaborator

    I have been trying to reproduce it with a local Sentinel build but it seems to work. Could you please provide us with your compiler version, build options, the configuration you are using, and any logs? You can configure the logging level by passing a logger::level value to connection's constructor. Any other info you may find important is welcome.

    Best,
    Ruben.

  3. madkote commented on Jul 27, 2026

    @madkote
    Author

    I have been trying to reproduce it with a local Sentinel build but it seems to work. Could you please provide us with your compiler version, build options, the configuration you are using, and any logs? You can configure the logging level by passing a logger::level value to connection's constructor. Any other info you may find important is welcome.

    Best, Ruben.

    yes, is it enough docker-compose, and main.cpp as in one of my repos?

  4. anarthal commented on Jul 27, 2026

    @anarthal
    Collaborator

    Yep, that's great.

  5. anarthal commented on Jul 29, 2026

    @anarthal
    Collaborator

    Yup, please remember to send us the link to the docker compose file so we can investigate! Thanks

  6. madkote commented on Jul 30, 2026

    @madkote
    Author

    hi @anarthal , thanks for quick response.
    the issue was the way channel is subscribed.

    DO

    req.subscribe({MESSAGE_CHANNEL});

    DO NOT

    req.push("SUBSCRIBE", MESSAGE_CHANNEL);
  7. madkote commented on Jul 30, 2026

    @madkote
    Author

    QUESTION 1
    docs say:

          // The response must be consumed without suspending the
          // coroutine i.e. without the use of async operations.
          for (push_view elem : push_parser(resp.value())) {
             std::cout << "Received message from channel " << elem.channel << ": " << elem.payload
                       << "\n";
          }

    why it can not be? because of context switch?

    the scenario is:

    • have a asio:channel ACHANNEL(...);
    • spawn a task for pubsub receiver with pubsub channel name and ACHANNEL (to process these message somewhere else.
    • spawn a task process(ACHANNEL) -> the processor of message received from pubsub.

    if elem.payload cannot be processed in a coroutine like co_await process(elem.payload);, then it must be pushed to normal queue (asio channel with co_await will be against docs above). As result the receive() function will become poll one, process, poll one, ...

    is there any good approach for that? receiver example is functional, but away from real use cases.

    Thanks!

  8. madkote commented on Jul 30, 2026

    @madkote
    Author

    QUESTION 2

    • connection in async_receive2() will try to reconnect forever?
    • is there a possibility to limit attempts or by time?

    during reconnect, it is possible to set a cancellation timer for async_exec, but setting a cancellation timer for async_receive2() might be ambiguous - timeout due to reconnect or timeout because nothing received.

    maybe there is a setting to connection for number of attempts or duration for reconnecting?

    are these settings relevant for my question?

    std::chrono::steady_clock::duration resolve_timeout = std::chrono::seconds{10};
    std::chrono::steady_clock::duration connect_timeout = std::chrono::seconds{10};
    

    If I docker kill every redis node (but sentinels are still running) without explicit timer, async_exec and async_receive2 running now forever. Same is if also sentinels are killed.

    (Boost.Redis) Sentinel at sentinel-1:26379: connection establishment error: Host not found (non-authoritative), try again later [asio.netdb:2]
    (Boost.Redis) Sentinel at 172.25.0.5:26379 resolved the server address to redis-node-3:6379
    ....
    Sentinel at 172.25.0.5:26379: connection establishment error: Connect timeout. [boost.redis:18]
      Sentinel at sentinel-1:26379: connection establishment error: Host not found (non-authoritative), try again later [asio.netdb:2]
    ...
    

    how to enforce to throw an error after some period of time or after number of attempts

  9. anarthal commented on Jul 31, 2026

    @anarthal
    Collaborator

    Hi!

    the issue was the way channel is subscribed.

    So the issue described here is solved, right?

    // The response must be consumed without suspending the
    // coroutine i.e. without the use of async operations.

    why it can not be? because of context switch?

    Sort of. Once you yield, more pushes may arrive, and they will get stored into the response object that you passed to set_receive_response. This creates all sort of pitfalls. For example:

          for (push_view elem : push_parser(resp.value())) {
               // WRONG! resp's iterators will get invalidated between yields, but the loop doesn't know it, causing a crash
               co_await channel.send(elem.payload); 
          }

    Bear in mind that it is actually async_run, rather than async_receive2, the one that modifies the receive response. Think of async_receive2 as a "block until there are any pushes available".

    Something you could do is using Asio channels and try_send, for example. You might miss notifications if your consumer is slower than the producer, but you should be able to handle this anyway - server disconnections cause the same effect. Would that suit you? If it doesn't, let me know and I'll try to write something else for you.

    connection in async_receive2() will try to reconnect forever?

    It is not async_receive2 that does the reconnections, but async_run. But yes, it will try to reconnect forever. There is no way to limit it in terms of number of reconnections. However, you can limit it by time using a timeout using the usual Asio tools. The idea here would be running your entire coroutine application wrapped in an asio::cancel_after, with your timeout. For example:

    asio::awaitable<void> your_application(connection& conn)
    {
       // Use async_receive2 and any other tasks
    }
    
    asio::awaitable<void> co_main()
    {
       // Create a connection
       auto ex = co_await asio::this_coro::executor;
       connection conn{ex};
       config cfg{};  // customize as required
    
       // Run your application and connection::async_run() in parallel
       co_await asio::experimental::make_parallel_group(
          asio::co_spawn(ex, your_application(conn)),
          conn.async_run(cfg))
          .async_wait(asio::experimental::wait_for_one(), asio::deferred);
    }
    
    int main()
    {
       asio::io_context ctx;
       // Kill everything after 30 seconds
       asio::co_spawn(ctx, co_main(), asio::cancel_after(30s, [](std::exception_ptr exc) {
                         if (exc)
                            std::rethrow_exception(exc);
                      }));
    }

    Let me know if you want me to expand on the last one.

    Best,
    Ruben.

  10. mzimbres commented on Aug 1, 2026

    @mzimbres
    Collaborator

    why it can not be? because of context switch?

    You can suspend if you make a copy of the response copy

    // Wrong (as Ruben explained)
    for (push_view elem : push_parser(resp.value())) { co_await channel.async_send(...); }
    
    // Correct: make a copy.
    auto value = resp.value();
    for (push_view elem : push_parser(value)) { co_await channel.async_send(...); }

    Notice however you cannot block async_receive2 with an async_exec on the same connection

    // Wrong
    awaitable receiver()
    {
      co_await conn.async_receive2();
      co_await conn.async_exec(req, resp);
    }

    While async_exec is suspended waiting for its response, the channel might have become full of further pushes. When that happens, the connection waits for async_receive2 to drain the channel, but that won't happen because async_exec is blocking it. That is a deadlock as both functions are waiting on each other for completion.

    If you feel the need to call async_exec after async_receive2 use a second connection.

  11. madkote commented on Aug 3, 2026

    @madkote
    Author

    Thanks Ruben @anarthal ! yes, the issue can be closed - it was not a bug or so - actually I had to read docs more carefully.

    1. process received messages - actually I am storing them in a queue and process afterwards with asio channel.
    2. For production grade, there are long running tasks with their dependencies, so killing everything every 30sec does not seem to be a good solution.

    I use async_receive as poll mechanism from outer loop, so I can control errors and reconnections, but I need to subscribe manually on the new connection (once returned from sentinel). I need to try, maybe async_receive will also work req.subscribe({MESSAGE_CHANNEL}); - so I can skip part of managing channels.

    But imho async_receive2 should have some mechanism to detect connection errors and also provide error code.

    • wait for server push, awake and process, continue
    • wait for server push, host lost, reconnect with configurable timeout
      • reconnect and continue
      • error and propagate error code
      • reconnect happens to host given from sentinels or normal host

    Receiving a proper error code would allow to steer application in the right way, recover and/or provide meaningful error. Just reconnect for4ever is kind of "die silently".

    does it make sense?

  12. madkote commented on Aug 3, 2026

    @madkote
    Author

    why it can not be? because of context switch?

    You can suspend if you make a copy of the response copy

    // Wrong (as Ruben explained)
    for (push_view elem : push_parser(resp.value())) { co_await channel.async_send(...); }

    // Correct: make a copy.
    auto value = resp.value();
    for (push_view elem : push_parser(value)) { co_await channel.async_send(...); }

    Notice however you cannot block async_receive2 with an async_exec on the same connection

    // Wrong
    awaitable receiver()
    {
    co_await conn.async_receive2();
    co_await conn.async_exec(req, resp);
    }

    While async_exec is suspended waiting for its response, the channel might have become full of further pushes. When that happens, the connection waits for async_receive2 to drain the channel, but that won't happen because async_exec is blocking it. That is a deadlock as both functions are waiting on each other for completion.

    If you feel the need to call async_exec after async_receive2 use a second connection.

    @mzimbres thanks for you reply. Currently I store parsed messages in a queue and process them with asio after. I just wanted to know the reason why not "co_await" directly on each parsed messages from response. Thanks for explanation.

    and Yes, I use different connection for exec and receive. but thanks for hint.

    the only issue I have it ability to control reconnect mechanism in async_receive2. a simple timer and cancel on async_exec is working excellent.

  13. anarthal commented on Aug 5, 2026

    @anarthal
    Collaborator

    I use async_receive as poll mechanism from outer loop, so I can control errors and reconnections, but I need to subscribe manually on the new connection (once returned from sentinel). I need to try, maybe async_receive will also work req.subscribe({MESSAGE_CHANNEL}); - so I can skip part of managing channels.

    I understand that what you'd like to get here are notifications of connection events, like "disconnected" (with a proper error code) and "reconnected", in addition to the regular pushes, right? The problem with the current async_receive implementation is that it gets cancelled on disconnection, and nothing more. This has the implication that if async_receive wasn't running when the disconnection happened, you will miss the disconnection event.

    But imho async_receive2 should have some mechanism to detect connection errors and also provide error code.

    wait for server push, awake and process, continue
    wait for server push, host lost, reconnect with configurable timeout
    reconnect and continue
    error and propagate error code
    reconnect happens to host given from sentinels or normal host

    I want to note here that async_receive2 does not control reconnection anyhow. It is async_run the one that handles reconnections. This means that semantics like "wait for server push, host lost, reconnect with configurable timeout" will likely need to be implemented on your side, provided that we supply a proper primitive to detect disconnection events.

    To do this, we would need to implement a new function to wait for reconnection events to happen. For example, async_wait_reconnections:

    // What happened?
    enum class event_type {
       disconnect,
       reconnect,
    };
    
    // Waits for a connect/disconnect event to happen
    asio::awaitable<event_type> connection::async_wait_reconnections();

    With that done, "wait for server push, host lost, reconnect with configurable timeout" can be implemented as:

    • You launch the waiter task normally.
    • In parallel, you launch a task to wait for reconnections. After you've seen a disconnect event, you wait for either the timeout you choose to elapse, or for a reconnection to happen.
    • You race both tasks using parallel_group.

    Would this scheme work for you?

  14. anarthal commented on Aug 5, 2026

    @anarthal
    Collaborator

    reconnect happens to host given from sentinels or normal host

    BTW I didn't get what you mean with this one.

  15. madkote commented on Aug 11, 2026

    @madkote
    Author

    reconnect happens to host given from sentinels or normal host

    BTW I didn't get what you mean with this one.

    this is pars of async_run as I understand now. thanks.

  16. madkote commented on Aug 11, 2026

    @madkote
    Author

    With that done, "wait for server push, host lost, reconnect with configurable timeout" can be implemented as:

    You launch the waiter task normally.
    In parallel, you launch a task to wait for reconnections. After you've seen a disconnect event, you wait for either the timeout you choose to elapse, or for a reconnection to happen.
    You race both tasks using parallel_group.
    

    Would this scheme work for you?

    actually that would provide a mechanism. One question, once reconnect is detected, that task for receive must be canceled and started again?

    can you maybe point me to async_receive2 implementation? and how is it connected with async_exec.

    as for API, I would prefer async_receive2 has internal event of reconnect, like a message from redis, currently there 3 (?) connected, disconnect, and payload as such. when parse gives messages of specifc type, it is clear what needs to be done (reconnect, etc) then there is no need for two tasks. I do similar approach now, where I provide artificial message, to detect events (incomplete message, multiple messages, etc)

  17. anarthal commented on Aug 11, 2026

    @anarthal
    Collaborator

    I think we did consider the dual API for receive at some point but @mzimbres was not very keen on it. Do you still feel the same about it?

  18. anarthal commented on Aug 11, 2026

    @anarthal
    Collaborator

    async_receive2 in essence reads messages from a channel. async_run reads from the socket and delivers pushes to the channel when it encounters them.

  19. mzimbres commented on Aug 12, 2026

    @mzimbres
    Collaborator

    One question, once reconnect is detected, that task for receive must be canceled and started again?

    You don't need to cancel to restore pubsub state. The library does that on behalf of the users.

    can you maybe point me to async_receive2 implementation?

    async_receive2 is pretty simple, it is basically the receive end of an asio::experimental::channel. We don't even need a channel to implement it but Asio lacks a simpler notification mechanism at the moment.

    and how is it connected with async_exec.

    In essence

    • async_receive2: waits for async_run to push events in a channel that is internal to the connection.
    • async_exec: pushes resquests into an internal queue and waits on a timer for notification that the response arrived.

    All IO operations, connection managements etc. is owned by async_run.

    as for API, I would prefer async_receive2 has internal event of reconnect, like a message from redis, currently there 3 (?) connected, disconnect, and payload as such. when parse gives messages of specifc type, it is clear what needs to be done (reconnect, etc) then there is no need for two tasks. I do similar approach now, where I provide artificial message, to detect events (incomplete message, multiple messages, etc)

    IMO async_receive2 should not be notified of any events that are not related to RESP3 pushes. To be notified of reconnect events you can set redis::config::reconnect_wait_interval to zero and call async_run in a loop (perhaps we need an example for this @anarthal).

    awaitable reconnect(std::shared<connection> conn)
    {
       auto ex = asio::this_coro::executor;
       steady_time timer{ex};
    
       while (cond) {
          auto [ec] = co_await conn->async_run(conf, as_tuple);
    
          // Perform here the actions you need after a disconnection.
    
          timer.expires_after(2s);
          co_await timer.async_wait();
       }
    }
  20. anarthal commented on Aug 13, 2026

    @anarthal
    Collaborator

    Actually, that's not gonna work as written because we reset active subscriptions when we re-run. Since we state nothing regarding this behavior in the docs, we can always change it. We would need to add some more docs and tests to verify that re-running works as intended for all cases. But it's definitely an option.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions