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


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="benwilson512" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/benwilson512/120/1457_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  benwilson512
                  </h3>
		          </div>
						
			          <div class="user-title">
									<span>Author of Craft GraphQL APIs in Elixir with Absinthe</span>
			          </div>
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Can you talk about your use case for the GenServer? GenServers are single threaded, that’s just what they are, there’s no getting around that. There’s probably a way to solve your problem without using a single GenServer, but we can’t recommend one without details about what it does.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="91745" data-batch-url="/posts/batch_likers">
                        2
                      </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/genserver-processing/15691/12">Post #11</a>
	                </div>
	            </div>
              <div id="likers-container-91745" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="91745"
                     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="91749" data-post-id="91749">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="ayhan.rashidov" src="/assets/icons/user-9f439610.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  ayhan.rashidov
                    <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><a class="mention" href="/u/benwilson512" rel="nofollow">@benwilson512</a> I have provided an example above. Let’s say that 5 people make a post request at the same time. For this example they will receive the response of the calculation immediately. But let’s say that each calculation takes 5 seconds. So in this case the first post request will be replied in 5 seconds. The second one will take 10 seconds and so on. I need to make them receive their responses in 5 seconds. That calculations for each of them have to be made at the same time not one by one. I am not sure if I could explain it.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="91749" 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/genserver-processing/15691/13">Post #12</a>
	                </div>
	            </div>
              <div id="likers-container-91749" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="91749"
                     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="91755" data-post-id="91755">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="benwilson512" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/benwilson512/120/1457_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  benwilson512
                  </h3>
		          </div>
						
			          <div class="user-title">
									<span>Author of Craft GraphQL APIs in Elixir with Absinthe</span>
			          </div>
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p><a class="mention" href="/u/ayhan.rashidov" rel="nofollow">@ayhan.rashidov</a> What I’m trying to understand is why the calculation needs to happen in a GenServer. What is the calculation, can it just be done in each user’s request process? Can it be a query on an ets table? We can’t recommend options if we don’t know what the computation is.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="91755" 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/genserver-processing/15691/14">Post #13</a>
	                </div>
	            </div>
              <div id="likers-container-91755" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="91755"
                     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="91756" data-post-id="91756">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="ayhan.rashidov" src="/assets/icons/user-9f439610.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  ayhan.rashidov
                    <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>This is just an example. Let’s say that the calculation must happen in the GenServer. This is the way I have to do it.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="91756" 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/genserver-processing/15691/15">Post #14</a>
	                </div>
	            </div>
              <div id="likers-container-91756" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="91756"
                     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="91757" data-post-id="91757">
  <section>
    <div class="post-wrap">


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

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>A single GenServer process can only ever work sequentially. If you need concurrency you need to spawn multiple processes.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="91757" 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/genserver-processing/15691/16">Post #15</a>
	                </div>
	            </div>
              <div id="likers-container-91757" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="91757"
                     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="91760" data-post-id="91760">
  <section>
    <div class="post-wrap">


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

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<aside class="quote no-group" data-username="ayhan.rashidov" data-post="15" data-topic="15691">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/letter_avatar_proxy/v4/letter/a/d9b06d/48.png" class="avatar"> ayhan.rashidov:</div>
<blockquote>
<p>This is the way I have to do it.</p>
</blockquote>
</aside>
<p>The point is that each request should already be running in it’s own process. Therefore each isolated request can make the call independently (and be blocked) and then has to wait for it’s own call to return. So things are already inherently concurrent.</p>
<p>By introducing a <strong>single</strong> GenServer that <strong>all</strong> requests have to go through you have created a bottleneck.</p>
<p>So the  question becomes, <strong>what is the benefit that this bottleneck gives you</strong>?</p>
<blockquote>
<p>That calculations for each of them have to be made at the same time not one by one.</p>
</blockquote>
<p>So have each request do its own calculations …</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="91760" data-batch-url="/posts/batch_likers">
                        2
                      </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/genserver-processing/15691/17">Post #16</a>
	                </div>
	            </div>
              <div id="likers-container-91760" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="91760"
                     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="91763" data-post-id="91763">
  <section>
    <div class="post-wrap">


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

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>If it has to run in a genserver then you could run a pool of that type of genserver and checkout 1 each time work needs to be run. Making it nonblocking to the extent of how many are in your pool. Otherwise GensServer will always be sequential in execution.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="91763" 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/genserver-processing/15691/18">Post #17</a>
	                </div>
	            </div>
              <div id="likers-container-91763" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="91763"
                     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 #17"></div>
  </section>
</div>
    <div class="postbit" id="91801" data-post-id="91801">
  <section>
    <div class="post-wrap">


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

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>There is a popular misconception that <code>GenServer</code> provides a means to structure programs, hide information etc. This is not the case. Elixir and Erlang programs are structured as modules containing functions. If you need to “do calculations in one place”, you use a function, not a server. If you have requirements for shared state then the particulars of those requirements determine the solution.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="91801" data-batch-url="/posts/batch_likers">
                        8
                      </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/genserver-processing/15691/19">Post #18</a>
	                </div>
	            </div>
              <div id="likers-container-91801" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="91801"
                     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 #18"></div>
  </section>
</div>
    <div class="postbit" id="91836" data-post-id="91836">
  <section>
    <div class="post-wrap">


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

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Some playground code to explore the some of the effects:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule Demo do

  @delay 2000

  defp report(index, base_time, start_time, end_time) do
    offset = :timer.now_diff(start_time, base_time)
    duration = :timer.now_diff(end_time, start_time)
    IO.puts("#{index}: offset: #{offset}μs dur: #{duration}μs")
  end

  def wrap_fun(base_time) do
    fn {fun, index} -&gt;
      fn -&gt;
        start_time = :erlang.timestamp()
        result = fun.()
        report(index, base_time, start_time, :erlang.timestamp())
        result
      end
    end
  end

  def do_it(a,b) do
    Process.sleep(@delay)
    a + b
  end

  def direct_fun({{a,b}, index}) do
    {fn -&gt; do_it(a,b) end, index} # i.e. call function directly
  end

  def sequential(requests) do
    base_time = :erlang.timestamp()
    requests
    |&gt; Enum.map(&amp;direct_fun/1)    # i.e. function will be called directly
    |&gt; Enum.map(wrap_fun(base_time))
    |&gt; Enum.map(&amp;(&amp;1.())) # RUN functions to process requests sequentially one at a time
  end

  def concurrent(requests) do
    base_time = :erlang.timestamp()
    requests
    |&gt; Enum.map(&amp;direct_fun/1)    # i.e. function will be called directly
    |&gt; Enum.map(wrap_fun(base_time))
    |&gt; Enum.map(&amp;Task.async/1)    # LAUNCH tasks to RUN requests concurrently
    |&gt; Enum.map(&amp;(Task.await(&amp;1)))# and block until ALL tasks are finished
  end

  def to_call_fun(pid) do
    fn {data, index} -&gt;
      {
      fn -&gt;
        GenServer.call(pid, data, :infinity) # i.e. have GenServer call function
      end,
      index
      }
    end
  end

  def constrained(requests, pid) do
    base_time = :erlang.timestamp()
    requests
    |&gt; Enum.map(to_call_fun(pid))  # i.e. use GenServer to call do_it function
    |&gt; Enum.map(wrap_fun(base_time))
    |&gt; Enum.map(&amp;Task.async/1)     # LAUNCH tasks to RUN requests concurrently
    |&gt; Enum.map(&amp;(Task.await(&amp;1))) # and block until ALL tasks are finished
  end
end

defmodule DemoSequential do

  def init(args) do
    {:ok, args}
  end

  def handle_call({a,b}, _from, state),
    do: {:reply, Demo.do_it(a,b), state}

  def handle_cast(:stop, state),
    do: {:stop, :normal, state}

  def terminate(reason, state) do
    IO.puts "#{inspect __MODULE__} terminate: #{inspect reason} #{inspect state}"
  end

end

defmodule DemoConcurrent do

  def init(args) do
    {:ok, args}
  end

  def launch_task(from, a, b) do
    Task.start(fn -&gt;
      result = Demo.do_it(a,b)
      GenServer.reply(from, result)
    end)
  end

  def handle_call({a,b}, from, state) do
     launch_task(from, a, b)
     {:noreply, state}
  end

  def handle_cast(:stop, state),
    do: {:stop, :normal, state}

  def terminate(reason, state) do
    IO.puts "#{inspect __MODULE__} terminate: #{inspect reason} #{inspect state}"
  end

end

requests =
  1..10
  |&gt; Enum.chunk_every(2, 2, :discard)
  |&gt; Enum.map(&amp;List.to_tuple/1)
  |&gt; Enum.with_index(1)

IO.puts("Each tuple is a {{a,b}, index} request")
IO.inspect(requests)

{:ok, pid_sequential} = GenServer.start_link(DemoSequential,[])
{:ok, pid_concurrent} = GenServer.start_link(DemoConcurrent,[])

IO.puts("Sequential processing")
IO.inspect(Demo.sequential(requests))

IO.puts("Concurrent - requests are processed concurrently (and independently)")
IO.inspect(Demo.concurrent(requests))

IO.puts("Constrained - concurrently running requests served sequentially")
IO.inspect(Demo.constrained(requests, pid_sequential))

IO.puts("Constrained - concurrently running requests served concurrently")
IO.inspect(Demo.constrained(requests, pid_concurrent))

GenServer.cast(pid_concurrent, :stop)
GenServer.cast(pid_sequential, :stop)
Process.sleep(500)
</code></pre>
<pre><code class="lang-plaintext">$ elixir demo.exs
Each tuple is a {{a,b}, index} request
[{{1, 2}, 1}, {{3, 4}, 2}, {{5, 6}, 3}, {{7, 8}, 4}, {{9, 10}, 5}]
Sequential processing
1: offset: 2μs dur: 2001419μs
2: offset: 2003665μs dur: 2000581μs
3: offset: 4004330μs dur: 2000679μs
4: offset: 6005107μs dur: 2000903μs
5: offset: 8006094μs dur: 2001040μs
[3, 7, 11, 15, 19]
Concurrent - requests are processed concurrently (and independently)
1: offset: 2224μs dur: 2000612μs
2: offset: 2228μs dur: 2000650μs
3: offset: 2230μs dur: 2000656μs
4: offset: 2232μs dur: 2000660μs
5: offset: 2234μs dur: 2000665μs
[3, 7, 11, 15, 19]
Constrained - concurrently running requests served sequentially
1: offset: 46μs dur: 2000500μs
2: offset: 55μs dur: 4001751μs
3: offset: 59μs dur: 6002516μs
4: offset: 62μs dur: 8003581μs
5: offset: 65μs dur: 10004541μs
[3, 7, 11, 15, 19]
Constrained - concurrently running requests served concurrently
1: offset: 53μs dur: 2001087μs
2: offset: 63μs dur: 2001112μs
3: offset: 68μs dur: 2001116μs
4: offset: 71μs dur: 2001120μs
5: offset: 75μs dur: 2001122μs
[3, 7, 11, 15, 19]
DemoConcurrent terminate: :normal []
DemoSequential terminate: :normal []
$
</code></pre> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="91836" 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/genserver-processing/15691/20">Post #19</a>
	                </div>
	            </div>
              <div id="likers-container-91836" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="91836"
                     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>