Connection pool (feat. RDBMS vs DynamoDB)

Falcon·2021년 5월 11일
1

aws

목록 보기
4/33
post-thumbnail

🎯 Goal

  • Connection Pool 에 대해 이해한다.
  • RDBMS와 DynamoDB의 Connection 운영 차이점에 대해 이해한다.

🚨 다음과 같은 상황을 방지하기 위해 이 글을 읽어야합니다.

  • DB에서 상당히 많은 오버헤드가 DB Connection 객체의 생성/해제에서 온다.
  • Connection 객체 생성이 불가능해질 경우, DB내부에서 발생한 오류로 응답코드 500Internal Server Error 로 처리한다 (디버깅이 쉽지 않음). 진짜 개빡치는 상황

Connection Pool

Connection

DB도 서버/클라이언트 구조를 갖기 때문에 DB에 쿼리를 하기 위한 클라이언트 - 서버간 연결 객체가 존재하는데 이 연결 객체를 Connection 라고한다.

Connection 의 한계

쿼리 한번마다 Connection 객체를 생성/해제 한다고 가정해보면 서버의 오버헤드가 커질 수 밖에 없다.
Connection Pool 은 이러한 오버헤드를 줄이기 위한 기술이다.

⚙️ Connection Pool 동작 방식 ⚙️

미리 Connection 객체를 여러개 만들어놓고, 쿼리 요청할때마다 하나씩 '빌려주자' (borrow)
쿼리가 끝나면 다시 '되갚아라' (release)

  1. Client Query 요청
  2. Connection Pool 로부터 Connection 객체 빌림
  3. 쿼리 요청
  4. 쿼리 결과 응답 (DB Server -> Client)
  5. 빌렸던 Connection 객체 Connection Pool 에 반환.

Pool 이란 단어하면 필자는 'Swimming Pool' 이 먼저 떠오른다. 그렇다. Connection Pool 은 그냥 Conneciton 객체를 모아둔 풀장이다.

👨‍💻 MySQL 예제 코드 (node.js)

const mysql = require('mysql2');
const settings = require('./settings.js');
// server 구동시 Connection Pool 생성
const connectionPool = mysql.createPool(settings);

// query 할 때마다 Connection 객체를 얻어옴.
module.exports = function getConnection(callback) {
    connectionPool.getConnection((error, connection)=> {
        if (error) {
          // 오류 발생시 얻어온 connection 객체 바로 반환
            connection.release();
            console.log('DB Pool Connection Failed!');
            console.error(error);
        } else {
          // 정상적으로 받아올 경우 Conneciton 객체 빌려오기 성공!
            callback(connection);
        }
    });
}

DynamoDB 예제 코드 (node.js)

//DynamoDB API 객체로 HTTP Request 생성 도구라고 보면 된다.
const dynamoDBClient = new DynamoDB.DocumentClient({region: process.env.AWS_REGION, apiVersion: "latest"});

const parameter = {
  //.... 생략
};

  try {
    //HTTP Request - Response
   	const result = await dynamoDBClient.get(parameter).promise();
  } catch (error) {
      	next(error);
  }

RDBMS vs DynamoDB

성격이 너무나도 다른 두 DBMS를 Connection 객체 운영 관점에서 비교해보자.

RDBMS

한번 Connection 객체를 생성하면 로직이 끝나는 순간까지 그 연결을 유지하고 해제한다.
|| Connection Pool 로부터 미리 만들어져있는 Connection 객체를 빌려쓰고 반환한다.

DynamoDB

HTTP Request - Response 동안에만 연결이 유지된다.
(query, scan , getItem 등의 쿼리 사용시 connection 객체가 생성되고 요청이 마무리되는 시점까지만 객체가 유지된다.)

DynamoDB is a web service, and interactions with it are stateless. Applications do not need to maintain persistent network connections. Instead, interaction with DynamoDB occurs using HTTP(S) requests and responses.

- AWS Document

👉 인스턴스당 1개의 DynamoDB client object 를 갖는 것이 효율적이다. (재활용)

DyanmoDB는 자체적으로 풀링된 HTTP Client 를 사용하여 Connection 객체 생성/해제 오버헤드를 최소화한다.


🔗 Reference

DB Connection Management Difference between RDB and DynamoDB - StackOverFlow

Characteristics of DynamoDB - AWS Document

profile
I'm still hungry

0개의 댓글