title: Slow reads on MongoDB from Spark - weird task allocation
body: <p>I have a MongoDB 4.2 cluster with 15 shards; the database stores a sharded collection of 6GB (i.e., about 400MB per machine).</p>
  <p>I'm trying to read the whole collection from Apache Spark, which runs on the same machine. Spark's application runs with <code>--num-executors 8</code> and <code>--executor-cores 6</code>; the connection is made through the spark-connector by configuring the MongoShardedPartitioner.</p>
  <p>Besides the reading being very slow (about 1.5 minutes; but, as far as I understand, full scans are generally bad on MongoDB), I'm experiencing this weird behavior in Spark's task allocation:</p>
  <p><a href="https://i.stack.imgur.com/3iQMi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3iQMi.png" alt="Task allocation" /></a></p>
  <p>The issues are the following:</p>
  <ol>
  <li>For some reason, only one of the executors starts reading from the database, while all the others wait 25 seconds to begin their readings. The red bars correspond to &quot;Task Deserialization Time&quot;, but my understanding is that they are simply idle (if there are concurrent stages, these executors work on something else and then come back to this stage only after the 25 seconds).</li>
  <li>For some other reason, after some time the concurrent allocation of tasks is suspended and then it resumes altogether (at about 55 seconds from the start of the job); you can see it in the middle of picture, as a whole bunch of tasks is started at the same time.</li>
  </ol>
  <p>Overall, the full scan could be completed in far less time if tasks were allocated properly.</p>
  <p>What is the reason for these behaviors and who is responsible (is it Spark, the spark-connector, or MongoDB)? Is there some configuration parameter that could cause these problems?</p>