public async Task ScaleDownForJobConfiguration() { DateTimeOffset now = DateTimeOffset.UtcNow; DateTimeOffset windowOfTime = now.AddHours(-2); IEnumerable <JobSummary> jobSummaries = await _jobManagement.GetNonCompletedJobsWithinTimeFrame(windowOfTime, now); if (jobSummaries == null) { string errorMessage = "Failed to fetch job summaries that are still running within the last hour"; _logger.Error(errorMessage); throw new RetriableException(errorMessage); } List <string> jobDefinitionIdsStillActive = jobSummaries.Select(m => m.JobType).Distinct().ToList(); IEnumerable <CosmosDbScalingConfig> cosmosDbScalingConfigs = await GetAllConfigs(); IList <CosmosDbScalingCollectionSettings> settingsToUpdate = new List <CosmosDbScalingCollectionSettings>(); foreach (CosmosDbScalingConfig cosmosDbScalingConfig in cosmosDbScalingConfigs) { CosmosDbScalingCollectionSettings settings = await _scalingConfigRepositoryPolicy.ExecuteAsync(() => _cosmosDbScalingConfigRepository.GetCollectionSettingsByRepositoryType(cosmosDbScalingConfig.RepositoryType)); bool jobActive = cosmosDbScalingConfig.JobRequestUnitConfigs.Any(item => jobDefinitionIdsStillActive.Contains(item.JobDefinitionId)); bool proceed = !settingsToUpdate.Any(m => m.Id == cosmosDbScalingConfig.Id); if (proceed && !jobActive) { if (!settings.IsAtBaseLine) { settingsToUpdate.Add(settings); } } } if (!settingsToUpdate.IsNullOrEmpty()) { foreach (CosmosDbScalingCollectionSettings settings in settingsToUpdate) { try { int?minimumRequestUnitsAllowed = await GetMinimumThroughput(settings.CosmosCollectionType); if (minimumRequestUnitsAllowed.HasValue && settings.MinRequestUnits < minimumRequestUnitsAllowed.Value) { settings.MinRequestUnits = minimumRequestUnitsAllowed.Value; } settings.CurrentRequestUnits = await ScaleCollection(settings.CosmosCollectionType, settings.MinRequestUnits, settings.MaxRequestUnits); await UpdateCollectionSettings(settings); } catch (Exception ex) { throw new RetriableException($"Failed to scale down collection for repository type '{settings.CosmosCollectionType}'", ex); } } await _cacheProviderPolicy.ExecuteAsync(() => _cacheProvider.RemoveAsync <List <CosmosDbScalingConfig> >(CacheKeys.AllCosmosScalingConfigs)); } }