영리의 테크블로그

AI 이미지 생성 프로젝트 ( AI Seller ) - [5] / 서버 분산 처리 본문

dev/AISeller

AI 이미지 생성 프로젝트 ( AI Seller ) - [5] / 서버 분산 처리

영리0 2024. 11. 6. 12:56

서버 분산 처리 시도와 실패

기존의 시연 연상

 

기존 로드밸런싱 구성 X



 

NGINX를 이용한 로드밸런싱 시도

처음에는 NGINX를 사용하여 여러 ComfyUI 서버에 요청을 분산하려 했다.

upstream comfyui_servers {
    server localhost:8188;
    server localhost:8189;
    server localhost:8190;
    server localhost:8191;
}

server {
    listen 80;

    location /api/ {
        proxy_pass http://comfyui_servers;
    }
}

 

실패 원인 

ComfyUI 서버는 WebSocket 연결을 통해 작업 상태를 확인해야 하는데

NGINX에서 요청을 분산하면 WebSocket 연결이 복잡해져 상태를 관리하는데 쉽지 않았다.

 - 각각의 포트의 return 이 달랐는데 이거를 프론트에 보내려 하다가 결국 실패하였다... ( 밤샘 😹 ) 

 

마음에 들지는 않지만 node.js 백엔드 단에서 직접 로드밸런싱을 구현하기로 하였다.

만약 20개의 요청이 들어오면 비동기 처리로 5개씩 4개의 서버에 요청하는 방식이다.

 

 

 

성공 영상



수동 로드밸런서 소스코드

 

async processImage(type, file, customBackground = null, progressCallback = null) {
    console.log('=== processImage 시작 ===');
    const serverUrl = this.getNextServer();
    this.serverQueues.get(serverUrl).push(file);
    try {
        if (progressCallback) progressCallback(10);
        const uploadResult = await this.uploadImage(file, serverUrl);
        if (progressCallback) progressCallback(30);

        let backgroundUploadResult = null;
        if (type === 'background' && customBackground) {
            backgroundUploadResult = await this.uploadImage(customBackground, serverUrl);
        }

        if (progressCallback) progressCallback(50);
        const workflow = this.getWorkflow(type);
        const modifiedWorkflow = this.modifyWorkflow(workflow, {
            inputImage: uploadResult.name,
            backgroundImage: backgroundUploadResult?.name
        });

        if (progressCallback) progressCallback(70);
        const promptResult = await this.executeWorkflow(modifiedWorkflow, serverUrl);
        if (progressCallback) progressCallback(90);
        const result = await this.waitForResult(promptResult.prompt_id, serverUrl);
        if (progressCallback) progressCallback(100);

        return {
            ...result,
            serverUrl
        };
    } finally {
        const queue = this.serverQueues.get(serverUrl);
        const index = queue.indexOf(file);
        if (index > -1) queue.splice(index, 1);
    }
}