하루 안에 끝나던 분석 배치가 하루를 넘기기 시작했다. 코드가 느려진 건 아니었다. 분석할 작업은 늘었는데 처리하는 ECS 태스크가 여전히 하나뿐이었다.

태스크를 10개로 고정하면 당장은 풀린다. 하지만 작업이 없는 시간에도 10개가 놀게 된다. (서버비는 아껴야 한다.) 그래서 대기열에 남은 작업 수를 CloudWatch 커스텀 메트릭으로 보내고, 그 메트릭에 건 Alarm으로 ECS Fargate 태스크 수를 1개와 10개 사이에서 자동으로 줄였다 늘렸다 하게 바꿨다.

SDK 대신 Alarm을 택한 이유

시스템은 Spring 기반 MSA이고, 배치 전용 모듈 두 개가 ECS Fargate 위에서 돈다.

  • 모듈 A는 Redshift 테이블을 조회해 작업 목록을 Queue에 쌓는다.

  • 모듈 B는 A의 Queue에서 작업을 pull해 분석한 뒤 Redshift 테이블에서 해당 row를 지운다.

분석 속도는 B의 태스크 수에 비례한다. 처음에는 대기열을 쥐고 있는 A가 AWS SDK로 B 서비스의 태스크 수를 직접 바꾸려 했다.

사전 테스트에서 바로 문제가 나왔다. SDK로 조정 정책을 건드리니 ECS가 필요한 태스크를 모두 새로 띄운 뒤 기존 태스크를 전부 지워 버렸다. 1개로 돌다가 4개를 추가하면 5개가 새로 뜨고 돌던 1개가 내려가는 식이다. 기존 태스크가 분석 중이던 작업은 그대로 끊긴다.

서비스 배포 설정(최소 실행 작업 비율 100%, 최대 200%)대로 새 배포를 할 때와 똑같은 동작이라, 태스크 수 조정이 아니라 새 배포로 처리됐을 가능성이 있다. 당시 어떤 API를 어떻게 호출했는지 기록이 없어 원인은 확정하지 못했다. 결국 A는 숫자만 던지고, 태스크 수는 ECS Service Auto Scaling이 CloudWatch Alarm을 받아 조절하도록 구조를 바꿨다.

flowchart LR
    A["모듈 A<br/>@Scheduled 5분"] -->|PutMetricData<br/>RecommendationTargetCount| M["CloudWatch<br/>ECS/CustomMetrics"]
    M --> H["Alarm: High-RecommendationTargetCount<br/>최소값 >= 10, 2/2"]
    M --> E["Alarm: Empty-RecommendationTargetCount<br/>최대값 <= 0, 2/2"]
    H -->|Set to 10 tasks| S["ECS Service B<br/>cbp-inf-opti-aws-recm"]
    E -->|Set to 1 task| S

메트릭 전송부터 ECS 스케일링 설정까지

먼저 A 모듈에 CloudWatch SDK를 넣었다.

dependencies {
	implementation 'software.amazon.awssdk:cloudwatch:2.22.9'
}

CloudWatchClient를 빈으로 등록할 때 자격 증명은 DefaultCredentialsProvider에 맡겨 Fargate 태스크 역할을 그대로 쓴다.

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;

import java.util.Objects;

@Configuration
@EnableAutoConfiguration
public class AwsConfiguration {

    private final String defaultRegion;

    public AwsConfiguration(@Value("${cloud.aws.region.static}") String defaultRegion) {
        this.defaultRegion = defaultRegion;
    }

    @Bean
    public CloudWatchClient cloudWatchClient() {
        return CloudWatchClient.builder()
                .region(Region.of(defaultRegion))
                .credentialsProvider(DefaultCredentialsProvider.create())
                .build();
    }
}

이제 5분마다 남은 작업 수를 세어 ECS/CustomMetrics 네임스페이스의 RecommendationTargetCount 메트릭으로 보낸다.

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
import software.amazon.awssdk.services.cloudwatch.model.Dimension;
import software.amazon.awssdk.services.cloudwatch.model.MetricDatum;
import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataRequest;
import software.amazon.awssdk.services.cloudwatch.model.StandardUnit;

@Profile({"prd", "dev"})
@Configuration
@Slf4j
@RequiredArgsConstructor
public class CmmtOptiMetricJob {

    private final CmmtRecmQueueRepository cmmtRecmQueueRepository;
    private final CmmtRecmDao cmmtRecmDao;
    private final CloudWatchClient cloudWatchClient;
    private final String NAMESPACE = "ECS/CustomMetrics";
    private final String METRIC_NAME = "RecommendationTargetCount";
    private final String DIMENSION_NAME = "ServiceName";
    private final String DIMENSION_VALUE = "cbp-inf-opti-aws";

    @Scheduled(fixedDelay = 300000) // 매 5분
    public void putRecommendationTargetCountMetricToCloudWatch() {
        int queueTargetCount = cmmtRecmQueueRepository.getRecommendationTargetQueue().size();
        int tableTargetCount = cmmtRecmDao.selectRecommendationTargetCount(); // 대기열 테이블 레코드 개수 조회
        // Queue에 남아 있으면 Queue 크기를, Queue가 비었으면 Redshift 대기열 테이블 건수를 보낸다
        int recommendationTargetCount = queueTargetCount > 0 ? queueTargetCount : tableTargetCount;

        Dimension dimension = Dimension.builder()
                .name(DIMENSION_NAME)
                .value(DIMENSION_VALUE)
                .build();

        MetricDatum datum = MetricDatum.builder()
                .metricName(METRIC_NAME)
                .unit(StandardUnit.COUNT)
                .value((double) recommendationTargetCount)
                .dimensions(dimension)
                .build();

        PutMetricDataRequest request = PutMetricDataRequest.builder()
                .namespace(NAMESPACE)
                .metricData(datum)
                .build();

        cloudWatchClient.putMetricData(request);
    }
}

여기서 한 가지 장치가 있다. B는 분석을 완전히 마친 뒤에야 Redshift row를 지우기 때문에 테이블 건수에는 아직 처리 중인 작업도 들어 있다. Queue가 비어도 메트릭은 바로 0이 되지 않고 마지막 분석이 끝난 뒤에야 0으로 떨어진다. Scale In이 돌고 있는 작업을 끊지 않는 이유다.

이 메트릭 하나에 Alarm 두 개를 걸었다. 둘 다 기간 5분, 데이터 포인트 2/2(10분 내 2개), 누락된 데이터는 무시(경보 상태 유지)로 맞췄고 통계와 조건만 나눴다.

Alarm통계조건연결한 조정 정책
High-RecommendationTargetCount최소>= 10정확히 10 작업
Empty-RecommendationTargetCount최대<= 0정확히 1 작업

Scale Out Alarm은 5분 구간의 최소값을 보므로 값이 잠깐 튀어서는 반응하지 않는다. Scale In Alarm은 최대값을 보므로 작업이 하나라도 남아 있으면 줄이지 않는다. 2/2 데이터 포인트 조건 덕분에 두 Alarm 모두 해당 상태가 10분 동안 이어져야 움직인다.

원래 생각은 대기열이 0이 아니면 바로 Scale Out하는 것이었지만 실제 임계값은 10으로 잡았다. 작업이 몇 건 안 남았을 때 태스크 10개를 띄우는 건 낭비라고 봤기 때문이다.

작업 목록이 쌓였을 때 Scale Out을 수행할 Alarm

작업 목록이 비었을 때 Scale In을 수행할 Alarm

B 서비스에서는 자동 크기 조정을 켜고 태스크 범위를 최소 1개, 최대 10개로 잡았다. 조정 정책은 둘 다 단계 조정(Step Scaling)으로 두고 앞의 Alarm을 연결했다.

  • High-RecommendationTargetCount는 경보 조건 하한 10 ~ +infinity일 때 Set to 10 tasks로 설정.

  • Empty-RecommendationTargetCount는 경보 조건 -infinity ~ 상한 0일 때 Set to 1 tasks로 설정.

  • 휴지 기간은 둘 다 300초.

몇 개를 더하는 대신 정확한 태스크 개수를 지정한 건 작업이 쌓이면 10개, 비면 1개라는 두 상태만 있으면 되기 때문이다.

비용은 용량 공급자 전략으로 한 번 더 줄였다. 원하는 태스크를 1로 두고 공급자 두 개를 섞었다.

용량 공급자기본(base)가중치(weight)
FARGATE10
FARGATE_SPOT01

base는 먼저 채울 최소 태스크 수, weight는 그 이후 나머지를 나누는 비율이다. FARGATE weight가 0이라 첫 태스크 1개만 일반 Fargate에 뜨고 Scale Out으로 늘어나는 9개는 전부 Fargate Spot으로 간다. 상시 도는 1개는 안정적인 쪽에, 몰릴 때만 붙는 9개는 싼 쪽에 둔 셈이다.

동작 확인과 남은 숙제

대기열에 작업이 쌓이자 B 태스크가 Fargate Spot으로 9개 늘어 기본 1개와 합쳐 10개가 됐다.

태스크 start

작업 목록이 모두 비자 서비스는 9개를 내리고 Fargate 태스크 1개만 남겼다.

태스크 stop

Scale In Alarm도 In alarm에서 시작해 작업이 들어오자 OK로 바뀌었고, 대기열이 완전히 빈 뒤 다시 In alarm으로 돌아왔다.

Alarm 모니터링


아직 손보지 못한 부분이 두 개 있다.

  1. 늘어난 9개가 전부 Fargate Spot이라 AWS가 회수하면 분석 중에 태스크가 멈춘다. 이때 B가 pull해 간 작업이 다시 대기열로 돌아가는지 아직 확인하지 않았다.

  2. 상태가 1개와 10개뿐이라 1~9건이 남은 구간에서는 직전에 떠 있던 태스크 수가 그대로 유지된다. 작업량에 맞춰 세밀하게 늘리려면 단계를 더 쪼개야 한다.