Executive Summary

Social Media Studio is a content ingestion and scheduled dispatch engine built with Elixir, Phoenix LiveView, Oban, and PostgreSQL. It converts raw blog copy (Markdown or scraped web URLs) into platform-tailored social media posts, runs automated grounding audits, and manages editorial approvals before dispatching to external networks.

The core challenge was not generating the variants, but guaranteeing that network retries, container crashes, and third-party rate limits never cause duplicate social posts or queue stalls.

System Guarantees

  • Zero Duplicate Dispatches: Idempotency enforced at the database layer via PostgreSQL partial unique indexing.
  • Non-Poisoning Backoff: Upstream HTTP 429 Retry-After headers mapped to native Oban queue snoozes.
  • Strict Boundary Control: Domain-level 403 refusal on unapproved content and pre-publish constraint checks immediately before socket transmission.

Architecture & Demo

The system is separated into two decoupled OTP contexts:

  1. Content Context: Handles Markdown parsing, remote URL scraping via Floki (executed outside database transactions to prevent connection pool exhaustion), Gemini 2.5 variant generation with Decimal token accounting, and automated factual grounding audits (VerifyGroundingWorker).
  2. Publishing Context: Governs editorial state transitions (draft → approved → scheduled), transactional slot scheduling, and background queue dispatching.
[ Ingress: LiveView / REST API ]
                │
                ▼
  [ Content Context: Ingestion ]
    ├── URL Scraping (Floki)
    ├── Gemini 2.5 Flash Generation
    └── VerifyGroundingWorker (Factual Audit)
                │
                ▼
 [ Publishing Context: Review Gate ]
    └── Rejects unapproved variants (HTTP 403)
                │
                ▼
   [ Oban Queue: PublishWorker ]
    ├── Pre-Publish Constraint Guard
    ├── PostgreSQL Idempotency Check (SELECT ... FOR UPDATE)
    └── SocialPublisher Behaviour Seam
                │
        ┌───────┴───────┐
        ▼               ▼
[ Telegram Bot API ]  [ Mock Adapters (X, LinkedIn) ]

Core Engineering Deep Dives

1. Hardware-Level Idempotency Under Worker Crash

In distributed queuing, a common failure mode occurs when a worker successfully pushes a message to an external API (like Telegram), but the process receives a SIGKILL or OOM crash right before marking the job complete in the database. When the queue manager boots back up, it reschedules the job, creating a duplicate post.

To make duplicate dispatches physically impossible under network or host failure, we pushed idempotency down to the PostgreSQL engine using a partial unique index:

CREATE UNIQUE INDEX publish_attempts_active_slot_index 
ON publish_attempts (slot_id) 
WHERE status IN ('pending', 'success');

When PublishWorker executes, it performs a transactional check with row locking:

# lib/flyrank_capstone_social_studio/publishing/workers/publish_worker.ex
def execute(%Oban.Job{args: %{"slot_id" => slot_id}}) do
  Repo.transaction(fn ->
    case Publishing.get_slot_with_lock(slot_id) do
      %{status: :published} ->
        # Slot is already marked published; exit cleanly
        {:ok, :already_published}

      slot ->
        dispatch_with_idempotency_guard(slot)
    end
  end)
end

If an upstream retry attempts to publish the same slot again, the query short-circuits with a 200 OK without re-engaging the external network adapter:

{
  "status": "already_published",
  "slot_id": "7f9188a2-d8c9-445b-a81d-bca541913165",
  "external_id": "telegram-msg-9142",
  "note": "Short-circuited without invoking external adapter."
}

2. Upstream Rate-Limit Snoozing (HTTP 429)

Third-party APIs have strict burst quotas. Hard crashes on rate limits poison worker queues, while generic exponential backoffs tie up concurrency slots or hammer the API too early.

The worker parses upstream HTTP 429 Retry-After headers and translates them directly into Oban snoozes:

case SocialPublisher.dispatch(slot) do
  {:ok, result} ->
    Publishing.record_success(slot, result)
    {:ok, result}

  {:error, %{status: 429, retry_after: seconds}} ->
    # Oban suspends this job without failing it; slot is unreserved for 'seconds'
    {:snooze, seconds}

  {:error, permanent_failure} ->
    Publishing.record_failure(slot, permanent_failure)
    {:error, permanent_failure}
end

3. Decoupling External APIs via Elixir Behaviours

To prevent Telegram-specific formatting rules (such as its 4,096 UTF-8 character limit and HTML entity parsing) from tangling with the core publishing engine, external networks are isolated behind a dynamic behavior:

# lib/flyrank_capstone_social_studio/publishing/social_publisher.ex
defmodule FlyrankCapstoneSocialStudio.Publishing.SocialPublisher do
  @callback dispatch(Slot.t()) :: {:ok, map()} | {:error, term()}

  def dispatch(slot) do
    adapter().dispatch(slot)
  end

  defp adapter do
    Application.get_env(
      :flyrank_capstone_social_studio,
      :social_publisher_adapter,
      FlyrankCapstoneSocialStudio.Publishing.Adapters.Telegram
    )
  end
end

This seam allows production workloads to dispatch to real Telegram channels while integration and load test suites swap in MockX and MockLinkedIn without mocking HTTP clients at the socket level.


Automated Verification

The entire lifecycle—from review gate refusals to race condition handling—is verified in ExUnit:

# Verify review barrier and worker dispatch logic
mix test test/flyrank_capstone_social_studio/publishing_test.exs

# Verify adapter boundary isolation and payload formatting
mix test test/flyrank_capstone_social_studio/adapter_test.exs
  • Test Suite Guarantee: Attempting to schedule any variant outside of the approved state immediately raises an HTTP 403 boundary rejection.
  • Idempotency Guarantee: Concurrent dispatch requests to an active slot serialize against publish_attempts_active_slot_index, returning a clean short-circuit rather than duplicate dispatches.

Retrospective & Trade-Offs

  • Single Workspace Scope: The initial architecture uses a unified database schema scoped to one team. Multi-tenant segregation with isolated tenant keys remains a future refactor.
  • Pre-Publish Guard: Adding validation right before socket transmission caught unexpected bugs where manual editor adjustments caused variants to exceed platform UTF-8 limits after initial approval.