Tips & Tricks

Claude Code로 A/B 테스트 구현하기

Claude Code를 사용한 A/B 테스트 구현 방법을 알아봅니다. 실용적인 코드 예시와 단계별 가이드를 포함합니다.

A/B 테스트 구현 전체 구조

A/B 테스트는 데이터 기반 의사결정에 필수적입니다. 하지만 올바른 통계 처리, 사용자 분배, 결과 추적까지 직접 구현하기는 쉽지 않습니다. Claude Code를 활용하면 통계적으로 정확한 A/B 테스트 인프라를 효율적으로 구축할 수 있습니다.

테스트 분배 엔진

> 사용자를 일관되게 A/B 그룹으로 분배하는 엔진을 만들어줘.
> 같은 사용자에게는 항상 같은 변형을 반환하도록 해줘.
import crypto from 'crypto';

interface Experiment {
  id: string;
  variants: { id: string; weight: number }[];
}

class ABTestEngine {
  private experiments: Map<string, Experiment> = new Map();

  register(experiment: Experiment) {
    const totalWeight = experiment.variants.reduce((sum, v) => sum + v.weight, 0);
    if (Math.abs(totalWeight - 100) > 0.01) {
      throw new Error('변형 가중치의 합은 100이어야 합니다');
    }
    this.experiments.set(experiment.id, experiment);
  }

  assign(experimentId: string, userId: string): string {
    const experiment = this.experiments.get(experimentId);
    if (!experiment) throw new Error(`실험을 찾을 수 없습니다: ${experimentId}`);

    const hash = crypto
      .createHash('md5')
      .update(`${experimentId}:${userId}`)
      .digest('hex');
    const bucket = parseInt(hash.substring(0, 8), 16) % 100;

    let cumulative = 0;
    for (const variant of experiment.variants) {
      cumulative += variant.weight;
      if (bucket < cumulative) return variant.id;
    }
    return experiment.variants[0].id;
  }
}

// 사용 예시
const engine = new ABTestEngine();
engine.register({
  id: 'checkout-flow',
  variants: [
    { id: 'control', weight: 50 },
    { id: 'new-design', weight: 50 },
  ],
});

React 컴포넌트에서 활용하기

import { createContext, useContext, useEffect } from 'react';

function useExperiment(experimentId: string): string {
  const engine = useContext(ABTestContext);
  const userId = useCurrentUserId();
  const variant = engine.assign(experimentId, userId);

  useEffect(() => {
    trackEvent('experiment_exposure', {
      experimentId,
      variant,
      userId,
    });
  }, [experimentId, variant, userId]);

  return variant;
}

// 컴포넌트에서 사용
function CheckoutPage() {
  const variant = useExperiment('checkout-flow');

  return variant === 'new-design'
    ? <NewCheckoutFlow />
    : <CurrentCheckoutFlow />;
}

결과의 통계 분석

A/B 테스트 결과를 올바르게 평가하려면 통계적 유의성 계산이 필요합니다.

interface TestResult {
  sampleSize: number;
  conversions: number;
}

function calculateSignificance(control: TestResult, treatment: TestResult) {
  const p1 = control.conversions / control.sampleSize;
  const p2 = treatment.conversions / treatment.sampleSize;

  const pooledP = (control.conversions + treatment.conversions) /
    (control.sampleSize + treatment.sampleSize);

  const se = Math.sqrt(
    pooledP * (1 - pooledP) * (1 / control.sampleSize + 1 / treatment.sampleSize)
  );

  const zScore = (p2 - p1) / se;
  const pValue = 2 * (1 - normalCDF(Math.abs(zScore)));

  return {
    controlRate: (p1 * 100).toFixed(2) + '%',
    treatmentRate: (p2 * 100).toFixed(2) + '%',
    improvement: (((p2 - p1) / p1) * 100).toFixed(2) + '%',
    pValue: pValue.toFixed(4),
    significant: pValue < 0.05,
  };
}

function normalCDF(x: number): number {
  const a1 = 0.254829592, a2 = -0.284496736;
  const a3 = 1.421413741, a4 = -1.453152027;
  const a5 = 1.061405429, p = 0.3275911;
  const sign = x < 0 ? -1 : 1;
  x = Math.abs(x) / Math.sqrt(2);
  const t = 1.0 / (1.0 + p * x);
  const y = 1.0 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-x * x);
  return 0.5 * (1.0 + sign * y);
}

정리

Claude Code를 활용하면 사용자 분배부터 통계적 유의성 계산까지, A/B 테스트 인프라를 일관되게 구축할 수 있습니다. 기능 플래그와의 연동은 기능 플래그 구현을, 애널리틱스 연동은 애널리틱스 구현 가이드를 참고하세요.

통계적 검정 이론에 대해서는 Evan Miller - Sample Size Calculator가 참고가 됩니다.

#Claude Code #A/B testing #analytics #React #statistics