<turbo-stream action="append" target="posts_list"><template>    <div class="postbit" id="240856" data-post-id="240856">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="peppy" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/peppy/120/23757_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  peppy
                    <span class="op-star" title="Thread Starter">
                      <img alt="OP" class="op-star-icon" src="/assets/thread-icons/thread-icon-thread-starter-df91e872.png" />
                    </span>
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Made a little progress today: figured out that RabbitMQ can’t save maps <code>%{}</code>, which is why nothing was publishing to the queue. I am using <code>:erlang.term_to_binary/binary_to_term</code> to encode/decode and it’s working pretty good so far.</p>
<p>However, a big problem still remains. How do I mark the batch as failed if the mysql insert fails? Here is what I have:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">def handle_batch(_, messages, _, _) do
    IO.inspect("handle batch")
    list = messages |&gt; Enum.map(fn e -&gt; :erlang.binary_to_term(e.data) end)
    case Exchat.Repo.insert_all(SaveChats,list) do
      {_, nil} -&gt;
        IO.inspect("Saved To Database - No Error Message Returned")
      {0, _} -&gt;
        IO.inspect{"Insert Failed"}
        Broadway.Message.failed(messages, "insert_failed")
    end
    messages
  end

</code></pre>
<p>If the insert fails, I try to use <code>Broadway.Message.failed(messages, "insert_failed")</code> but that doesn’t work.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="240856" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/need-help-building-simple-database-persistence-genstage-broadway/44957/12">Post #11</a>
	                </div>
	            </div>
              <div id="likers-container-240856" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="240856"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #11"></div>
  </section>
</div>
    <div class="postbit" id="241667" data-post-id="241667">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="peppy" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/peppy/120/23757_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  peppy
                    <span class="op-star" title="Thread Starter">
                      <img alt="OP" class="op-star-icon" src="/assets/thread-icons/thread-icon-thread-starter-df91e872.png" />
                    </span>
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Still need help with this. When I try running<code> Broadway.Mesage.failed(messages, "fail")</code>, I get this error message:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">[error] ** (FunctionClauseError) no function clause matching in Broadway.Message.failed/2
    (broadway 1.0.1) lib/broadway/message.ex:139: Broadway.Message.failed([%Broadway.Message{acknowledger: {BroadwayRabbitMQ.Producer, %AMQP.Channel{conn: %AMQP.Connection{pid: #PID&lt;0.568.0&gt;}, custom_consumer: {AMQP.SelectiveConsumer, #PID&lt;0.554.0&gt;}, pid: #PID&lt;0.577.0&gt;}, %{client: BroadwayRabbitMQ.AmqpClient, delivery_tag: 1, on_failure: :reject_and_requeue, on_success: :ack, redelivered: true}}, batch_key: :default, batch_mode: :bulk, batcher: :default, data: &lt;&lt;131, 116, 0, 0, 0, 4, 100, 0, 7, 109, 101, 115, 115, 97, 103, 101, 109, 0, 0, 0, 4, 97, 115, 100, 102, 100, 0, 6, 114, 111, 111, 109, 105, 100, 109, 0, 0, 0, 10, 114, 111, 111, 109, 58, ...&gt;&gt;, metadata: %{amqp_channel: %AMQP.Channel{conn: %AMQP.Connection{pid: #PID&lt;0.568.0&gt;}, custom_consumer: {AMQP.SelectiveConsumer, #PID&lt;0.554.0&gt;}, pid: #PID&lt;0.577.0&gt;}}, status: :ok}], "fail")
    (exchat 0.1.0) lib/exchat_web/broadway/savetest.ex:45: ExchatWeb.TestSave.handle_batch/4
    (broadway 1.0.1) lib/broadway/topology/batch_processor_stage.ex:100: Broadway.Topology.BatchProcessorStage.handle_batch/4
    (broadway 1.0.1) lib/broadway/topology/batch_processor_stage.ex:56: anonymous fn/5 in Broadway.Topology.BatchProcessorStage.handle_events/3
    (telemetry 0.4.3) /home/exchat/exchat/deps/telemetry/src/telemetry.erl:272: :telemetry.span/3
    (gen_stage 1.1.2) lib/gen_stage.ex:2471: GenStage.consumer_dispatch/6
    (stdlib 3.16.1) gen_server.erl:695: :gen_server.try_dispatch/4
    (stdlib 3.16.1) gen_server.erl:771: :gen_server.handle_msg/6
    (stdlib 3.16.1) proc_lib.erl:226: :proc_lib.init_p_do_apply/3
</code></pre>
<p>I’m trying to mark the entire batch as “failed”. I’m not sure why this isn’t working. I even added a handle_failed function.</p>
<pre data-code-wrap="elixir"><code class="lang-elixir"> def handle_failed(messages, "fail") do
    for message &lt;- messages do
      Broadway.Message.configure_ack(message, retry: true)
    end
  end
</code></pre>
<p>But I get an error for that as well:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">[error] ** (FunctionClauseError) no function clause matching in ExchatWeb.TestSave.handle_failed/2
    (exchat 0.1.0) lib/exchat_web/broadway/savetest.ex:55: ExchatWeb.TestSave.handle_failed([%Broadway.Message{acknowledger: {BroadwayRabbitMQ.Producer, %AMQP.Channel{conn: %AMQP.Connection{pid: #PID&lt;0.568.0&gt;}, custom_consumer: {AMQP.SelectiveConsumer, #PID&lt;0.554.0&gt;}, pid: #PID&lt;0.577.0&gt;}, %{client: BroadwayRabbitMQ.AmqpClient, delivery_tag: 1, on_failure: :reject_and_requeue, on_success: :ack, redelivered: true}}, batch_key: :default, batch_mode: :bulk, batcher: :default, data: &lt;&lt;131, 116, 0, 0, 0, 4, 100, 0, 7, 109, 101, 115, 115, 97, 103, 101, 109, 0, 0, 0, 4, 97, 115, 100, 102, 100, 0, 6, 114, 111, 111, 109, 105, 100, 109, 0, 0, 0, 10, 114, 111, 111, 109, 58, ...&gt;&gt;, metadata: %{amqp_channel: %AMQP.Channel{conn: %AMQP.Connection{pid: #PID&lt;0.568.0&gt;}, custom_consumer: {AMQP.SelectiveConsumer, #PID&lt;0.554.0&gt;}, pid: #PID&lt;0.577.0&gt;}}, status: {:error, %FunctionClauseError{args: nil, arity: 2, clauses: nil, function: :failed, kind: nil, module: Broadway.Message}, [{Broadway.Message, :failed, [[%Broadway.Message{acknowledger: {BroadwayRabbitMQ.Producer, %AMQP.Channel{conn: %AMQP.Connection{pid: #PID&lt;0.568.0&gt;}, custom_consumer: {AMQP.SelectiveConsumer, #PID&lt;0.554.0&gt;}, pid: #PID&lt;0.577.0&gt;}, %{client: BroadwayRabbitMQ.AmqpClient, delivery_tag: 1, on_failure: :reject_and_requeue, on_success: :ack, redelivered: true}}, batch_key: :default, batch_mode: :bulk, batcher: :default, data: &lt;&lt;131, 116, 0, 0, 0, 4, 100, 0, 7, 109, 101, 115, 115, 97, 103, 101, 109, 0, 0, 0, 4, 97, 115, 100, 102, 100, 0, 6, ...&gt;&gt;, metadata: %{amqp_channel: %AMQP.Channel{conn: %AMQP.Connection{pid: #PID&lt;0.568.0&gt;}, custom_consumer: {AMQP.SelectiveConsumer, #PID&lt;0.554.0&gt;}, pid: #PID&lt;0.577.0&gt;}}, status: :ok}], "fail"], [file: 'lib/broadway/message.ex', line: 139]}, {ExchatWeb.TestSave, :handle_batch, 4, [file: 'lib/exchat_web/broadway/savetest.ex', line: 45]}, {Broadway.Topology.BatchProcessorStage, :handle_batch, 4, [file: 'lib/broadway/topology/batch_processor_stage.ex', line: 100]}, {Broadway.Topology.BatchProcessorStage, :"-handle_events/3-fun-0-", 5, [file: 'lib/broadway/topology/batch_processor_stage.ex', line: 56]}, {:telemetry, :span, 3, [file: '/home/exchat/exchat/deps/telemetry/src/telemetry.erl', line: 272]}, {GenStage, :consumer_dispatch, 6, [file: 'lib/gen_stage.ex', line: 2471]}, {:gen_server, :try_dispatch, 4, [file: 'gen_server.erl', line: 695]}, {:gen_server, :handle_msg, 6, [file: 'gen_server.erl', line: 771]}, {:proc_lib, :init_p_do_apply, 3, [file: 'proc_lib.erl', line: 226]}]}}], :context_not_set)
    (broadway 1.0.1) lib/broadway/acknowledger.ex:102: Broadway.Acknowledger.handle_failed_messages/3
    (broadway 1.0.1) lib/broadway/topology/batch_processor_stage.ex:59: anonymous fn/5 in Broadway.Topology.BatchProcessorStage.handle_events/3
    (telemetry 0.4.3) /home/exchat/exchat/deps/telemetry/src/telemetry.erl:272: :telemetry.span/3
    (gen_stage 1.1.2) lib/gen_stage.ex:2471: GenStage.consumer_dispatch/6
    (stdlib 3.16.1) gen_server.erl:695: :gen_server.try_dispatch/4
    (stdlib 3.16.1) gen_server.erl:771: :gen_server.handle_msg/6
    (stdlib 3.16.1) proc_lib.erl:226: :proc_lib.init_p_do_apply/3
</code></pre>
<p>All I really need to do is mark the batch of messages as failed so they can be retried later. I actually don’t need to modify the failed messages or anything, so the <code>handle_failed</code> call might not even be necessary. Unfortunately, in both cases I don’t know how to do this in elixir. The script is almost finished except for this last part.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="241667" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/need-help-building-simple-database-persistence-genstage-broadway/44957/13">Post #12</a>
	                </div>
	            </div>
              <div id="likers-container-241667" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="241667"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #12"></div>
  </section>
</div>
    <div class="postbit" id="241704" data-post-id="241704">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="cmo" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/cmo/120/19618_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  cmo
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>As per the error message, <code>Broadway.Mesage.failed</code> doesn’t take a list of messages, just one. Try <code>Enum.map</code>/<code>for</code>.</p>
<p>IIRC, you only need <code>handle_failed</code> for messages that raise an exception.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="241704" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/need-help-building-simple-database-persistence-genstage-broadway/44957/14">Post #13</a>
	                </div>
	            </div>
              <div id="likers-container-241704" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="241704"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #13"></div>
  </section>
</div>
    <div class="postbit" id="241794" data-post-id="241794">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="josefrichter" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/josefrichter/120/19529_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  josefrichter
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Question from a different perspective:</p>
<p>Is something like GeenStage also used to prevent database overload?</p>
<p>Example: I have a simple GenServer that works as a “write buffer” or maybe a simple queue. It collects thousands of incoming records in its state, and then writes them in bulk, either every 100 records at once, or every 5 seconds. The main goal is not to do thousands of concurrent writes to postgres.</p>
<p>I was wondering, rather than trying to figure out how often the genserver should do the bulk write, whether maybe instead postgres should become a genstage consumer and request data as fast as it it able to process it? Is this a meaningful use case for GenStage?</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="241794" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/need-help-building-simple-database-persistence-genstage-broadway/44957/15">Post #14</a>
	                </div>
	            </div>
              <div id="likers-container-241794" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="241794"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #14"></div>
  </section>
</div>
    <div class="postbit" id="241897" data-post-id="241897">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="peppy" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/peppy/120/23757_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  peppy
                    <span class="op-star" title="Thread Starter">
                      <img alt="OP" class="op-star-icon" src="/assets/thread-icons/thread-icon-thread-starter-df91e872.png" />
                    </span>
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Awesome, I think I actually got the full script working the way I want now! I can build on that for other features later on, pretty neat.</p>
<p>Now I have a question about how to publish to RabbitMQ more efficiently. Right now, I am using these functions in my room_channel.ex script:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir"> def handle_in("new_msg", %{"body" =&gt; body}, socket) do
      :ok = publish(%{message: body, userid: String.to_integer(socket.assigns.user_id)})
      broadcast!(socket, "new_msg", %{body: body})
      {:noreply, socket}
  end

 def publish(chat_message) do
    # Receive chat room message map and publish it to RabbitMQ queue
    {:ok, connection} = AMQP.Connection.open
    {:ok, channel} = AMQP.Channel.open(connection)
    AMQP.Basic.publish(channel, "", "save_chats_queue", :erlang.term_to_binary(chat_message))
    AMQP.Connection.close(connection)
  end
</code></pre>
<p>The big question is about the <code>publish</code> function. As you can see, I’m opening and closing a connection every single time a message comes in. What is the correct way of doing this? Should I put this publish function in my Broadway/RabbitMQ script instead? I’m assuming that script always has a persistent connection to RabbitMQ already open, but I don’t know how to use it (the name of the connection/channel variables).</p>
<p>And if the connection to RabbitMQ fails, does the main Broadway script automatically reconnect?</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="241897" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/need-help-building-simple-database-persistence-genstage-broadway/44957/16">Post #15</a>
	                </div>
	            </div>
              <div id="likers-container-241897" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="241897"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #15"></div>
  </section>
</div>
    <div class="postbit" id="242795" data-post-id="242795">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="peppy" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/peppy/120/23757_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  peppy
                    <span class="op-star" title="Thread Starter">
                      <img alt="OP" class="op-star-icon" src="/assets/thread-icons/thread-icon-thread-starter-df91e872.png" />
                    </span>
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Still need help on this, can’t find any examples online for my case except for the basic tutorial example (which I’m using above), which I’m not sure works well for full production.</p>
<p>With the publish() function above, is the standard practice to be opening and closing connections every single time I post a message to RabbitMQ? Is RabbitMQ (and/or Elixir) going to be able to handle the constant opening/closing of connections like this if 1000s of messages come in each second?</p>
<p>And should I put this function in with my Broadway script, or just set up a separate module dedicated just for publishing to RabbitMQ and leave the Broadway script for receiving/processes messages from RabbitMQ?</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="242795" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/need-help-building-simple-database-persistence-genstage-broadway/44957/17">Post #16</a>
	                </div>
	            </div>
              <div id="likers-container-242795" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="242795"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #16"></div>
  </section>
</div>
    <div class="postbit" id="242801" data-post-id="242801">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="cmo" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/cmo/120/19618_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  cmo
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>I’ve not used Rabbit, but I don’t see why you would open and close a connection repeatedly.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="242801" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/need-help-building-simple-database-persistence-genstage-broadway/44957/18">Post #17</a>
	                </div>
	            </div>
              <div id="likers-container-242801" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="242801"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-last-post cat-last-post" title="Last post!"></div>
  </section>
</div>
</template></turbo-stream><turbo-stream action="replace" target="load-more-container"><template><div id="load-more-container" class="load-more-container">
    <span class="all-loaded">— All posts loaded —</span>
</div></template></turbo-stream>