title: Throttling akka-actor that keeps only the newest messages
body: <h1>Situation</h1>
  
  <p>I am using akka actors to update data on my web-client. One of those actors is solely repsonsible for sending updates concerning single <code>Agent</code>s. These agents are updated very rapidly (every 10ms). My goal now is to throttle this updating mechanism so that the newest version of every <code>Agent</code> is sent every 300ms.</p>
  
  <h1>My code</h1>
  
  <p>This is what I came up with so far:</p>
  
  <pre class="lang-scala prettyprint-override"><code>/**
    * Single agents are updated very rapidly. To limit the burden on the web-frontend, we throttle the messages here.
    */
  class BroadcastSingleAgentActor extends Actor {
  
      private implicit val ec: ExecutionContextExecutor = context.dispatcher
      private var queue = Set[Agent]()
  
      context.system.scheduler.schedule(0 seconds, 300 milliseconds) {
          queue.foreach { a =&gt;
              broadcastAgent(self)(a) // sends the message to all connected clients
          }
          queue = Set()
      }
  
      override def receive: Receive = {
          // this message is received every 10 ms for every agent present
          case BroadcastAgent(agent) =&gt; 
             // only keep the newest version of the agent
             queue = queue.filter(_.id != agent.id) + agent
      }
  
  }
  </code></pre>
  
  <h1>Question</h1>
  
  <p>This actor (<code>BroadcastSingleAgentActor</code>) works as expected, but I am not 100% sure if this is thread safe (updating the <code>queue</code> while potentionally clearing it). Also, this does not feel like I am making the best out of the tools akka provides me with. I found this <a href="http://letitcrash.com/post/28901663062/throttling-messages-in-akka-2" rel="nofollow noreferrer">article</a> (Throttling Messages in Akka 2), but my problem is that I need to keep the newest <code>Agent</code> message while dropping any old version of it. Is there an example somewhere similar to what I need?</p>