Le Duy Khuong

Chuỗi: seo-posthog · Phần 4

Năng suất & công cụ dev

Feature Flags & A/B Testing

Feature flags, experiments

2026-03-205 phút đọcVI

Feature Flags & A/B Testing

Mở đầu

"Nên hiển thị Related Posts hay SeriesBox cuối bài?" — Đây không phải câu hỏi anh có thể answer bằng opinion. Cần data. A/B testing cho phép hiển thị version A cho 50% users, version B cho 50% còn lại, rồi đo: version nào có engagement cao hơn?

PostHog tích hợp Feature Flags (bật/tắt tính năng per user) với Experiments (A/B testing với statistical analysis). Bài này giới thiệu cả hai — dù leduykhuong.com chưa implement, đây là tools quan trọng khi site grow.

Mục tiêu: Hiểu feature flags concept, cách PostHog thực hiện A/B test, và khi nào personal blog cần experimentation.


Feature Flags — Bật/Tắt tính năng

Feature flag = boolean hoặc variant gắn với user. Code check flag → hiển thị UI khác nhau:

Concept

// Pseudocode
if (posthog.isFeatureEnabled("new-toc-design")) {
  return <NewTableOfContents />;
} else {
  return <TableOfContents />;
}

User A thấy TOC mới, User B thấy TOC cũ — dựa trên flag evaluation.

Use Cases cho Personal Blog

FlagMô tảLý do
show-related-postsHiển thị related posts cuối bàiTest impact on "read another article" rate
new-search-uiSearch bar mới trên headerGradual rollout để catch bugs
reading-timeHiển thị estimated reading timeTest if it affects bounce rate
dark-mode-defaultDefault theme = darkTest user preference assumption

PostHog Feature Flag Types

TypeMô tảVí dụ
BooleanOn/Offshow-related-posts: true/false
MultivariateMultiple variantscta-text: "Read More" / "Continue" / "Next Article"
Percentage rolloutBật cho N% usersnew-feature: 10% → 50% → 100%
User propertyBật theo propertybeta-features: country === "VN"

A/B Testing — Measure Impact

A/B test = Feature flag + Statistical analysis.

Workflow

1. Hypothesis: "Related Posts cuối bài tăng % users đọc bài thứ 2"

2. Setup Experiment (PostHog):
   - Control: Không có Related Posts (current)
   - Variant: Có Related Posts
   - Goal metric: second_article_view event
   - Split: 50/50

3. Run: PostHog tự phân users vào Control/Variant

4. Wait: Đủ sample size (PostHog tính tự động)

5. Analyze: PostHog báo:
   - Control: 12% read second article
   - Variant: 18% read second article
   - Significance: 95% → statistical significant
   - Recommendation: Ship variant ✅

Statistical Significance

PostHog tự tính:

  • p-value — Probability kết quả xảy ra do chance (< 0.05 = significant)
  • Confidence interval — Range of likely true values
  • Sample size — Bao nhiêu users cần cho reliable result
  • Minimum detectable effect — Smallest improvement worth detecting

Rule of thumb: Với 500-1000 sessions/month, A/B test cần 2-4 tuần để reach significance. Nếu expected difference nhỏ (< 5%), cần lâu hơn.


Implementation trong Next.js

Cài PostHog Feature Flag

// Sử dụng PostHog SDK
import posthog from 'posthog-js';
 
function BlogPost({ post }) {
  const showRelatedPosts = posthog.isFeatureEnabled('show-related-posts');
 
  return (
    <article>
      {/* ... post content ... */}
 
      {showRelatedPosts && (
        <RelatedPosts currentSlug={post.slug} />
      )}
    </article>
  );
}

Static Export Challenge

leduykhuong.com dùng static export → HTML rendered at build time. Feature flags evaluate at client-side runtime:

"use client";
import { useEffect, useState } from "react";
import posthog from "posthog-js";
 
function ConditionalFeature({ children, flag }: { children: React.ReactNode; flag: string }) {
  const [enabled, setEnabled] = useState(false);
 
  useEffect(() => {
    setEnabled(posthog.isFeatureEnabled(flag) ?? false);
  }, [flag]);
 
  if (!enabled) return null;
  return <>{children}</>;
}

Trade-off: Feature xuất hiện sau hydration (flash). Cho UI-only features (related posts, reading time), acceptable. Cho structural changes (layout), cần careful handling.


Khi nào Personal Blog cần A/B Testing?

Nên test khi:

  1. Traffic đủ — ≥ 1000 sessions/month cho meaningful results
  2. Decision có impact — Change ảnh hưởng core metrics (engagement, retention)
  3. Uncertainty thật sự — Không rõ option nào tốt hơn
  4. Reversible — Có thể revert nếu variant kém

Không cần test khi:

  1. Low traffic — < 500 sessions/month → mất quá lâu cho significance
  2. Obvious improvement — Fix bug, improve load time (just do it)
  3. Personal preference — Color scheme anh thích → không cần data
  4. Infrastructure change — Upgrade framework, refactor code (no user-facing impact)

leduykhuong.com: Chưa cần, nhưng sẵn sàng

Với ~500-1000 sessions/month, A/B testing sẽ mất 3-4 tuần per test. Tuy nhiên, PostHog đã integrated — khi traffic grow, activation chỉ mất vài dòng code.

Priority khi sẵn sàng:

  1. Test "Related Posts" display → impact on multi-article reads
  2. Test blog listing layout (grid vs list) → impact on click-through
  3. Test CTA text ("Read More" vs "Continue Reading") → impact on engagement

Feature Flag Best Practices

1. Clean Up Flags

Feature flags là temporary — sau khi decision made, remove flag và ship winning variant. Stale flags = tech debt.

2. Name Convention

feature-name-variant (for experiments)
release-feature-name (for gradual rollout)

3. Default Safe

Flag defaults nên return CURRENT behavior:

const showNew = posthog.isFeatureEnabled('new-feature') ?? false;
// false = current behavior (safe default)

4. Server-side vs Client-side

EvaluationProsCons
Client-sideNo server needed, works with static exportFlash of content, slower evaluation
Server-sideNo flash, instantNeed server runtime

leduykhuong.com = static export → client-side only. Accept minor flash.


Thực hành

Bài tập 1: Create Feature Flag

PostHog → Feature Flags → New:

  • Name: show-reading-time
  • Type: Boolean
  • Rollout: 50%
  • Save

Bài tập 2: Check Flag Client-side

// Thêm vào component
useEffect(() => {
  console.log("Reading time flag:", posthog.isFeatureEnabled("show-reading-time"));
}, []);

Bài tập 3: Design Experiment

Thiết kế A/B test cho blog site:

  • Hypothesis: [statement]
  • Control vs Variant: [description]
  • Primary metric: [what to measure]
  • Sample size estimate: [how long to run]

Tóm tắt

  • Feature flags — Bật/tắt features per user. Types: boolean, multivariate, percentage, property-based.
  • A/B testing = Feature flag + Statistical analysis → data-driven decisions
  • PostHog Experiments tự tính p-value, confidence interval, sample size
  • Static export → client-side flag evaluation, accept minor flash
  • When to test — Traffic ≥ 1000/month, decision has impact, genuine uncertainty
  • Clean up flags — Remove after decision made. Stale flags = tech debt.

Bài tiếp theo

Kết thúc series PostHog Product Analytics. Series tiếp theo: Technical SEO — Bài 17 sẽ giải thích cách Google crawl, index, và rank websites — foundation knowledge cho mọi SEO work.

LDK

Le Duy Khuong

AI Transformation & Digital Strategy. Writing about agentic systems, engineering leadership, and building in public.