Developer documentation v1.x

Documentation

Waspito Feed Engine & Timeline Architecture

1. Architecture overview

The feed engine uses a multi-stage pipeline rather than relying on expensive SQL sorting across a large set of records and polymorphic relationships.

50k+ database items
        │
        ▼ Candidate retrieval via composite indexes
~150–200 candidate IDs
        │
        ▼ In-memory scoring: gravity decay + credibility bonus
Ranked sequence
        │
        ▼ Assembly: inject ads, suggested groups, doctors, and alerts
Interleaved feed
        │
        ▼ Batch hydration of the requested page slice
15 hydrated items delivered to Vue

Pipeline stages

  1. Candidate retrieval — Filter 50k+ database items down to approximately 150–200 relevant candidates.

  2. In-memory ranking — Score candidates based on engagement, user affinity, doctor verification, and time decay. Target execution time: under 15 ms.

  3. Synthetic interleaving — Insert health alerts, suggested groups, recommended doctors, and sponsored products at predefined positions.

  4. Hydration and slicing — Load only the 15 items needed for the requested page slice, avoiding N+1 queries.

2. Directory structure

Place feed-service files under app/Services/Feed/:

app/Services/Feed/
├── FeedManager.php                 # Main facade/orchestrator used by controllers
├── Contracts/
│   └── FeedRankerInterface.php     # Ranking algorithm contract
├── Engines/
│   ├── CandidateFetcher.php        # Fast candidate extraction (indexes only)
│   ├── FeedRanker.php              # Time-decay and engagement scoring
│   ├── FeedAssembler.php           # Interleaves ads, groups, doctors, and alerts
│   └── FeedHydrator.php            # Batch model hydration; prevents N+1 queries
├── DTOs/
│   └── FeedResult.php              # Standardized data transfer object
└── Support/
    └── TimelineItemEnum.php        # Card and feed type constants

3. Core pipeline components

Engines/CandidateFetcher.php — Candidate retrieval

  • Narrows the catalog to roughly 200 items a user may care about.

  • Queries only the timeline_items table using composite indexes.

  • Avoids polymorphic joins during candidate retrieval.

  • Fetches recent items (up to 14 days old), items from joined groups, verified-doctor posts, and globally pinned items.

Engines/FeedRanker.php — Scoring and ranking

Scores and sorts candidate items in memory using an edge-rank time-decay formula:

Final Score = (base_score + credibility_bonus) × Decay
Decay       = 1 / ((Age in Hours + 2) ^ 1.45)
  • Credibility boost: Items with human_verified = true receive an authority boost of +45.0 before decay is applied.

  • Pinned override: Items with is_pinned = true receive a priority score of 9,999,999 to ensure top placement.

Engines/FeedAssembler.php — Interleaving and card injection

Merges the ranked organic feed with promotional and discovery units without adding synthetic cards to the core content schema.

Position Feed unit
0 (top of page 1) Emergency/outbreak health advisory banner
4 Suggested groups carousel
7 and every 7th position thereafter Sponsored health products or pharmacy promotions
10 Vetted specialist recommendation cards

Engines/FeedHydrator.php — Batch eager loading

  • Resolves polymorphic models (for example, Article, GroupPost, and WaspitoGroup) only for the 15 items on the current page slice.

  • Collects IDs by model type and performs a single whereIn query per type.

  • Preserves the ranked sequence when returning hydrated models.

FeedManager.php — Orchestrator facade

Coordinates the feed lifecycle: checks the three-minute per-user feed cache, calls CandidateFetcher and FeedRanker on a cache miss, handles pagination offsets, hydrates the requested slice, and passes the slice to FeedAssembler.

4. Database schema and indexing

The timeline_items table stores denormalized routing keys and composite indexes for candidate retrieval.

Schema::create('timeline_items', function (Blueprint $table) {
    $table->bigIncrements('id');

    // Polymorphic content link (Article, GroupPost, etc.)
    $table->morphs('contentable');

    // Denormalized routing keys (avoids child-table joins during search)
    $table->unsignedBigInteger('group_id')->nullable()->index();
    $table->nullableMorphs('author'); // author_type and author_id (Doctor, User, Clinic)

    // Domain and credibility flags
    $table->boolean('human_verified')->default(false)->index();
    $table->boolean('is_pinned')->default(false);
    $table->boolean('is_active')->default(true);

    // Engagement and precalculated scoring
    $table->unsignedInteger('reactions_count')->default(0);
    $table->unsignedInteger('comments_count')->default(0);
    $table->unsignedInteger('shares_count')->default(0);
    $table->unsignedInteger('saves_count')->default(0);
    $table->float('base_score', 10, 2)->default(0);

    $table->timestamp('published_at')->nullable();
    $table->timestamps();

    // Composite indexes for fast retrieval
    $table->index(
        ['is_active', 'is_pinned', 'base_score', 'published_at'],
        'feed_rank_idx'
    );
    $table->index(
        ['group_id', 'is_active', 'published_at'],
        'group_feed_idx'
    );
});

5. Service registration

Bind FeedRankerInterface in app/Providers/AppServiceProvider.php:

use App\Services\Feed\Contracts\FeedRankerInterface;
use App\Services\Feed\Engines\FeedRanker;

public function register(): void
{
    $this->app->bind(FeedRankerInterface::class, FeedRanker::class);
}

6. Controller usage

Call FeedManager from the API controller:

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\TimelineItemResource;
use App\Services\Feed\FeedManager;
use App\Services\Feed\Support\TimelineItemEnum;
use Illuminate\Http\Request;

class TimelineController extends Controller
{
    public function index(Request $request, FeedManager $feedManager)
    {
        $page = (int) $request->input('page', 1);
        $perPage = (int) $request->input('per_page', 15);
        $user = $request->user(waspitoGuard());

        $result = $feedManager->getUserFeed($user, $page, $perPage);

        // Transform organic content models; pass synthetic cards through as-is.
        $transformedItems = $result->items->map(function ($unit) {
            if ($unit['feed_type'] === TimelineItemEnum::TYPE_CONTENT) {
                return [
                    'feed_type' => TimelineItemEnum::TYPE_CONTENT,
                    'data' => new TimelineItemResource($unit['data']),
                ];
            }

            return $unit;
        });

        return response()->json([
            'status' => 'success',
            'data' => $transformedItems,
            'pagination' => [
                'has_more' => $result->hasMore,
                'next_page' => $result->nextPage,
                'total_candidates' => $result->totalCandidates,
            ],
        ]);
    }
}

7. API response format

The API returns a flat array of typed objects. The frontend selects a card layout based on feed_type.

{
  "status": "success",
  "data": [
    {
      "feed_type": "health_banner",
      "data": {
        "title": "Community Health Alert",
        "summary": "Seasonal vaccination updates available at certified centers.",
        "cta_url": "/alerts/health-bulletin"
      }
    },
    {
      "feed_type": "content",
      "data": {
        "id": 142,
        "contentable_type": "App\\Models\\Article",
        "title": "Managing Hypertension: Dietary Guidelines",
        "author": {
          "name": "Dr. Sarah Adams",
          "human_verified": true
        }
      }
    },
    {
      "feed_type": "suggested_groups_carousel",
      "data": [
        { "id": 12, "name": "Diabetes Support Africa", "members_count": 3420 }
      ]
    },
    {
      "feed_type": "sponsored_product",
      "data": {
        "id": 901,
        "title": "Accu-Chek Instant Blood Glucose Meter",
        "link": "/pharmacy/devices/glucometer"
      }
    }
  ],
  "pagination": {
    "has_more": true,
    "next_page": 2,
    "total_candidates": 150
  }
}

8. Vue 2 frontend integration

Use Vue's dynamic <component :is="..."> pattern to keep card rendering separate from feed-type branching.

<template>
  <div class="timeline-container">
    <div v-for="(item, idx) in feedItems" :key="idx" class="feed-slot">
      <component
        :is="resolveCardComponent(item.feed_type)"
        :payload="item.data"
      />
    </div>
  </div>
</template>

<script>
import ArticleCard from '@/components/cards/ArticleCard.vue';
import GroupPostCard from '@/components/cards/GroupPostCard.vue';
import HealthBanner from '@/components/cards/HealthBanner.vue';
import SuggestedGroupsCarousel from '@/components/cards/SuggestedGroupsCarousel.vue';
import DoctorRecommendationCard from '@/components/cards/DoctorRecommendationCard.vue';
import SponsoredCard from '@/components/cards/SponsoredCard.vue';

export default {
  components: {
    ArticleCard,
    GroupPostCard,
    HealthBanner,
    SuggestedGroupsCarousel,
    DoctorRecommendationCard,
    SponsoredCard,
  },
  props: {
    feedItems: { type: Array, required: true },
  },
  methods: {
    resolveCardComponent(feedType) {
      const mapping = {
        content: (payload) =>
          payload.contentable_type && payload.contentable_type.indexOf('Article') !== -1
            ? 'ArticleCard'
            : 'GroupPostCard',
        health_banner: 'HealthBanner',
        suggested_groups_carousel: 'SuggestedGroupsCarousel',
        recommended_doctors_card: 'DoctorRecommendationCard',
        sponsored_product: 'SponsoredCard',
      };

      const component = mapping[feedType];
      return typeof component === 'function'
        ? component(this.payload)
        : (component || 'div');
    },
  },
};
</script>

9. Performance guarantees and edge rules

  • Counter caching: Do not call withCount(['reactions', 'comments']) in feed requests. Maintain counter columns (reactions_count, comments_count, and others) with atomic database increments such as increment().

  • Base-score maintenance: Recalculate timeline_items.base_score in a queued listener when users interact with an item:

    base_score = (reactions × 1)
               + (comments × 3)
               + (saves × 5)
               + (shares × 7)
               + (human_verified ? 45 : 0)
    
  • Feed cache invalidation: Cache the candidate ID sequence for three minutes per user. Reaction writes update the item's counters without invalidating or clearing the user's active page sequence.