private async Task <RangeValue> GetNextMaxAsyncInner(IAsyncDatabaseCommands databaseCommands, long calculatedCapacity) { var minNextMax = Range.Max; using (databaseCommands.ForceReadFromMaster()) using (databaseCommands.DisableAllCaching()) while (true) { try { ConflictException ce = null; JsonDocument document; try { document = await GetDocumentAsync(databaseCommands).ConfigureAwait(false); } catch (ConflictException e) { ce = e; document = null; } if (ce != null) { return(await HandleConflictsAsync(databaseCommands, ce, minNextMax, calculatedCapacity).ConfigureAwait(false)); } IncreaseCapacityIfRequired(ref calculatedCapacity); long min, max; if (document == null) { min = minNextMax + 1; max = minNextMax + calculatedCapacity; document = new JsonDocument { Etag = Etag.Empty, // sending empty etag means - ensure the that the document does NOT exists Metadata = new RavenJObject(), DataAsJson = RavenJObject.FromObject(new { Max = max }), Key = HiLoDocumentKey }; } else { var oldMax = GetMaxFromDocument(document, minNextMax, calculatedCapacity); min = oldMax + 1; max = oldMax + calculatedCapacity; document.DataAsJson["Max"] = max; } await PutDocumentAsync(databaseCommands, document).ConfigureAwait(false); return(new RangeValue(min, max)); } catch (ConcurrencyException) { //expected & ignored, will retry this // we'll try to increase the capacity ModifyCapacityIfRequired(ref calculatedCapacity); } } }