본문으로 건너뛰기

서버리스 함수

Connect Base 서버리스 함수 심화 가이드입니다.

지원 런타임

현재 ent 스키마의 runtime enum 은 두 가지만 지원합니다 (nodejs20, python311).

런타임버전패키지 매니저
Node.js20.xnpm, yarn, pnpm
Python3.11pip

📌 Go / .NET 런타임은 아직 백엔드에 추가되지 않았습니다.

Node.js 함수 작성

기본 구조

handler 시그니처는 handler(payload, context) 입니다. 첫 인자 payload 는 호출 시 보낸 JSON 객체 그 자체이며(별도 래퍼 객체로 감싸지 않음), 반환은 값(객체)을 그대로 리턴합니다.

javascript
// handler.js
export async function handler(payload, context) {
  const { email, name } = payload

  // 비즈니스 로직
  const result = await processData(payload)

  return { success: true, result }
}

외부 패키지 사용

javascript
// package.json
{
  "dependencies": {
    "axios": "^1.6.0",
    "lodash": "^4.17.21"
  }
}

// handler.js
import axios from 'axios'
import _ from 'lodash'

export async function handler(payload, context) {
  const response = await axios.get('https://api.example.com/data')
  const filtered = _.filter(response.data, { active: true })

  return { items: filtered }
}

Python 함수 작성

기본 구조

handler 시그니처는 handler(payload, context) 입니다. 첫 인자 payload 는 호출 시 보낸 JSON 객체 그 자체이며, 반환은 값(dict)을 그대로 리턴합니다.

python
# handler.py
def handler(payload, context):
    email = payload.get('email')

    # 비즈니스 로직
    result = process_data(payload)

    return { 'success': True, 'result': result }

외부 패키지 사용

# requirements.txt
requests==2.31.0
pandas==2.1.0
python
# handler.py
import requests
import pandas as pd

def handler(payload, context):
    response = requests.get('https://api.example.com/data')
    df = pd.DataFrame(response.json())

    return { 'rows': df.to_dict(orient='records') }

환경 변수

설정

콘솔에서 함수 > 설정 > 환경 변수에서 추가:

SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
[email protected]
SMTP_PASS=app_password

사용

환경변수/시크릿은 두 번째 인자 context.env 로 접근하는 것이 컨트랙트 표준입니다(Node.js 는 process.env 로도 동작).

javascript
// Node.js — context.env 가 표준 (process.env 도 동작)
const smtpHost = context.env.SMTP_HOST
python
# Python
smtp_host = context["env"]["SMTP_HOST"]

콜드 스타트 최적화

1. 패키지 최소화

필요한 패키지만 설치:

json
// ❌ 불필요한 패키지 포함
"dependencies": {
  "aws-sdk": "^3.0.0",  // 전체 SDK
  "lodash": "^4.17.21"
}

// ✅ 필요한 것만
"dependencies": {
  "@aws-sdk/client-s3": "^3.0.0",  // S3만
  "lodash.filter": "^4.6.0"  // filter만
}

2. 전역 초기화

DB 연결 등은 핸들러 밖에서 초기화:

javascript
// ✅ 전역에서 초기화 (재사용됨)
const db = new Database(process.env.DB_URL)

export async function handler(payload, context) {
  // db 재사용
  const result = await db.query('SELECT * FROM users')
  return { rows: result }
}

3. 번들 크기 최소화

javascript
// ❌ 전체 import
import * as _ from 'lodash'

// ✅ 필요한 함수만 import
import filter from 'lodash/filter'

에러 처리

javascript
export async function handler(payload, context) {
  try {
    const result = await riskyOperation()
    return { success: true, result }
  } catch (error) {
    console.error('Error:', error)  // 로그 기록
    return { success: false, error: error.message }
  }
}

타임아웃 설정

  • 기본 타임아웃: 30초
  • 최대 타임아웃: 5분으로 강제 클램핑 (invoke_service MaxTimeout). 그 이상 값을 콘솔에 입력해도 호출 시 5분으로 제한됩니다.

콘솔에서 함수 → 설정 → 타임아웃에서 변경