That line:
$limit = $data->range; // set new limit
should of course really be:
$limit = $data->key; // set new limit
I.e. we are using the field 'key' from the last record to set the new (exclusive) lower limit for the next query. Also of course, if 'key' is not unique, this method will not work because if you say > you will omit and 2nd and subsequent records with the same key value, and if you say >= you may get one or more of them repeated at the start of the next query.