class AwsAutoScalingService {

    @VisibleForTesting
    void checkLastScalingActivity(AmazonAutoScalingClient asClient, AmazonAutoScalingRetryClient asRetryClient, String autoScalingGroupName,
            Date timeBeforeASUpdate, Group group) throws AmazonAutoscalingFailed {
        if (group.getInstancesSize() > 0) {
            LOGGER.debug("Check last activity after AS update. Wait for the first if it doesn't exist. [asGroup: {}]", autoScalingGroupName);
            Optional<Activity> firstActivity;
            try {
                Waiter<DescribeScalingActivitiesRequest> autoscalingActivitiesWaiter = customAmazonWaiterProvider
                        .getAutoscalingActivitiesWaiter(asClient, timeBeforeASUpdate);
                autoscalingActivitiesWaiter.run(new WaiterParameters<>(new DescribeScalingActivitiesRequest().withAutoScalingGroupName(autoScalingGroupName)));
                DescribeScalingActivitiesResult describeScalingActivitiesResult = asRetryClient
                        .describeScalingActivities(new DescribeScalingActivitiesRequest().withAutoScalingGroupName(autoScalingGroupName));

                // if we run into InsufficientInstanceCapacity we can skip to waitForGroup because that method will wait for the required instance count
                firstActivity = describeScalingActivitiesResult.getActivities().stream().findFirst()
                        .filter(activity -> "failed".equals(activity.getStatusCode().toLowerCase()) &&
                                !activity.getStatusMessage().contains("InsufficientInstanceCapacity"));

            } catch (Exception e) {
                LOGGER.error("Failed to list activities: {}", e.getMessage(), e);
                throw new AmazonAutoscalingFailed(e.getMessage(), e);
            }

            if (firstActivity.isPresent()) {
                Activity activity = firstActivity.get();
                LOGGER.error("Cannot execute autoscale, because last activity is failed: {}", activity);
                throw new AmazonAutoscalingFailed(activity.getDescription() + " " + activity.getCause());
            }
        }
    }

}