C#
recommendation algorithms
tweets analysis
machine learning
social media tech

Recommendation Algorithms for tweets in C

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Recommending tweets is not a single algorithm. A production system usually combines several signals: who the user follows, which authors they engage with, what topics appear in the tweet, and how recent the tweet is. In C#, the practical starting point is often a simple hybrid scorer rather than a full collaborative-filtering system.

Define the Recommendation Problem First

Before writing code, decide what you are ranking:

  • tweets from followed accounts only
  • tweets from the whole network
  • replies and quote posts included or excluded
  • fresh tweets only, or older evergreen content too

These choices matter because tweet recommendation is usually more time-sensitive than movie or product recommendation. Recency is not a side factor. It is part of the ranking model.

A Simple Hybrid Score Works Well as a Baseline

A reasonable first implementation mixes:

  • author affinity
  • content similarity
  • engagement score
  • time decay

Here is a small C# model:

csharp
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5public record Tweet(
6    int Id,
7    int AuthorId,
8    string Text,
9    HashSet<string> Tags,
10    int Likes,
11    DateTime CreatedAtUtc);
12
13public record UserProfile(
14    int UserId,
15    HashSet<int> FollowedAuthors,
16    HashSet<string> InterestedTags,
17    Dictionary<int, double> AuthorAffinity);

Now a scorer:

csharp
1public static class TweetRanker
2{
3    public static double Score(UserProfile user, Tweet tweet, DateTime nowUtc)
4    {
5        double authorScore = user.AuthorAffinity.TryGetValue(tweet.AuthorId, out var affinity)
6            ? affinity
7            : 0.0;
8
9        double followBoost = user.FollowedAuthors.Contains(tweet.AuthorId) ? 2.0 : 0.0;
10
11        int sharedTags = tweet.Tags.Intersect(user.InterestedTags).Count();
12        double topicScore = sharedTags * 1.5;
13
14        double engagementScore = Math.Log(1 + tweet.Likes);
15
16        double ageHours = Math.Max(0.0, (nowUtc - tweet.CreatedAtUtc).TotalHours);
17        double recencyScore = Math.Exp(-ageHours / 24.0) * 3.0;
18
19        return authorScore + followBoost + topicScore + engagementScore + recencyScore;
20    }
21}

This is not fancy, but it is transparent and debuggable. That matters a lot when you are trying to understand why one tweet was ranked above another.

Ranking a Candidate Set

Given a candidate list, you can sort tweets by the computed score:

csharp
1var user = new UserProfile(
2    UserId: 1,
3    FollowedAuthors: new HashSet<int> { 10, 20 },
4    InterestedTags: new HashSet<string> { "dotnet", "csharp", "ai" },
5    AuthorAffinity: new Dictionary<int, double> { [10] = 3.0, [30] = 1.0 }
6);
7
8var tweets = new List<Tweet>
9{
10    new Tweet(1, 10, "New C# feature", new HashSet<string> { "csharp" }, 50, DateTime.UtcNow.AddHours(-1)),
11    new Tweet(2, 30, "AI trends", new HashSet<string> { "ai" }, 10, DateTime.UtcNow.AddHours(-2)),
12    new Tweet(3, 99, "Sports update", new HashSet<string> { "sports" }, 200, DateTime.UtcNow.AddHours(-1))
13};
14
15var ranked = tweets
16    .OrderByDescending(t => TweetRanker.Score(user, t, DateTime.UtcNow))
17    .ToList();
18
19foreach (var tweet in ranked)
20{
21    Console.WriteLine($"{tweet.Id}: {tweet.Text}");
22}

This baseline already captures an important truth: a tweet from a followed author about a topic the user likes is often more relevant than a globally popular tweet on an unrelated topic.

Content-Based Signals

Content-based recommendation focuses on the tweet itself. In a real system, the feature set may include:

  • hashtags
  • embeddings from the tweet text
  • language
  • media presence
  • topic clusters

If you want a lightweight start in C#, token or tag overlap is enough. For better quality, store a vector embedding per tweet and compare it to a user-interest vector using cosine similarity.

Conceptually:

csharp
1public static double CosineSimilarity(double[] a, double[] b)
2{
3    double dot = 0, normA = 0, normB = 0;
4    for (int i = 0; i < a.Length; i++)
5    {
6        dot += a[i] * b[i];
7        normA += a[i] * a[i];
8        normB += b[i] * b[i];
9    }
10    return dot / (Math.Sqrt(normA) * Math.Sqrt(normB));
11}

The embedding generation usually happens outside the ranking code, but the C# service can still consume those vectors efficiently.

Collaborative Filtering Comes Later

Collaborative filtering uses behavior from many users, such as likes, clicks, reposts, or dwell time. It can be effective, but it is a harder starting point because you need enough interaction data and enough infrastructure to maintain user-item features.

Typical collaborative signals include:

  • users who liked similar tweets
  • authors engaged with by similar users
  • co-occurrence between followed accounts and interacted topics

For a new system or a side project, a hybrid heuristic model is usually a better first version than trying to train matrix factorization immediately.

Candidate Generation and Final Ranking

Recommendation systems normally work in two stages:

  1. generate a manageable set of candidate tweets
  2. rank those candidates with a richer scoring model

Candidate generation can come from:

  • followed authors
  • trending topics
  • recently engaged clusters
  • similar users

The ranking stage then uses the scoring logic shown earlier. Keeping these stages separate helps performance and makes tuning easier.

Feedback Loops and Diversity

A tweet recommender can become narrow very quickly if it only reinforces past clicks. A user who clicks one AI post should not see only AI posts forever.

To control that, many systems add:

  • diversity penalties for near-duplicate tweets
  • caps per author
  • freshness requirements
  • exploration slots for unseen topics

These are ranking constraints, not afterthoughts.

Common Pitfalls

  • Starting with complex collaborative filtering before you have enough user interaction data.
  • Ignoring recency, even though tweet relevance decays quickly.
  • Ranking only by global engagement and drowning personalized content under viral posts.
  • Failing to separate candidate generation from final ranking, which makes the system slower and harder to tune.
  • Creating a feedback loop that over-optimizes one topic or one author and reduces feed diversity.

Summary

  • Tweet recommendation usually works best as a hybrid of author, topic, engagement, and recency signals.
  • A transparent scoring model in C# is a strong baseline and easy to debug.
  • Content-based features are often easier to start with than full collaborative filtering.
  • Separate candidate generation from ranking for better performance and cleaner design.
  • Add diversity and freshness rules early, because feed quality is not just about raw relevance score.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.