惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

H
Hacker News: Front Page
S
Secure Thoughts
N
News | PayPal Newsroom
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
T
Threatpost
N
News and Events Feed by Topic
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
A
Arctic Wolf
Cisco Talos Blog
Cisco Talos Blog
V2EX - 技术
V2EX - 技术
L
LINUX DO - 热门话题
C
Cyber Attacks, Cyber Crime and Cyber Security
P
Proofpoint News Feed
TaoSecurity Blog
TaoSecurity Blog
N
News and Events Feed by Topic
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Hacker News - Newest:
Hacker News - Newest: "LLM"
NISL@THU
NISL@THU
H
Heimdal Security Blog
Webroot Blog
Webroot Blog
Martin Fowler
Martin Fowler
The Hacker News
The Hacker News
Engineering at Meta
Engineering at Meta
MongoDB | Blog
MongoDB | Blog
A
About on SuperTechFans
Stack Overflow Blog
Stack Overflow Blog
B
Blog RSS Feed
Vercel News
Vercel News
Blog — PlanetScale
Blog — PlanetScale
Google Online Security Blog
Google Online Security Blog
Schneier on Security
Schneier on Security
Cyberwarzone
Cyberwarzone
小众软件
小众软件
V
V2EX
K
Kaspersky official blog
Security Archives - TechRepublic
Security Archives - TechRepublic
博客园 - 三生石上(FineUI控件)
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
C
Cisco Blogs
S
Schneier on Security
Recorded Future
Recorded Future
阮一峰的网络日志
阮一峰的网络日志
AI
AI
Microsoft Security Blog
Microsoft Security Blog
H
Help Net Security
Simon Willison's Weblog
Simon Willison's Weblog
I
InfoQ
G
Google Developers Blog
博客园_首页
Hugging Face - Blog
Hugging Face - Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Claprec: Machine Learning in Practice (4/6)
Kenan Sejmen · 2026-05-18 · via DEV Community

Series Roadmap


Building the Recommendation Engine: A Hybrid Approach to Personalization in Claprec

When building Claprec, the primary challenge wasn't just storing reviews; it was surfacing them. The landing page is the gateway to the platform, and a generic "latest posts" feed simply doesn't cut it when you're trying to build user retention. A system was needed that could handle the cold start problem, respect geographical relevance, and leverage user behavior - specifically, how much time a user spends consuming content.

In this post, I'm going to break down the architecture of the recommendation algorithm that powers the main feed. It's a hybrid system combining collaborative filtering via Matrix Factorization, geo-spatial heuristics, and other factors.


The Architecture: Strategies for Different Contexts

One of the first decisions I made was to avoid a "one size fits all" approach. The backend logic needs to pivot based on the client's state. Specifically, are we dealing with an authenticated user with or without location data, or an anonymous user?

The entry point handles these three distinct scenarios:

  1. Anonymous & No Location: The system defaults to a popularity contest, using recency as a fallback metric.
  2. Authenticated User: The architecture deploys a personalized ML-driven feed that prioritizes interests, followed by popularity and recency.
  3. Authenticated User & Location: The logic applies a personalized ML-driven feed that prioritizes geospatial factors, followed by interests, popularity, and recency.
// HigherCrudServiceReview.cs

public async Task<PaginatedResponse<DtoRelatedReview>> Recommended(BaseSearchDto search, UriBuilder uriBuilder, double? lat, double? lng, User? user)
{
  // ...

  return await PaginatedResultWithAttachedProperties(...);
}

Enter fullscreen mode Exit fullscreen mode

Handling Geo-Spatial Complexity

Before we even get to the Machine Learning, we have to solve the location problem. In Claprec, a review isn't just a point on a map. It can be attached to a specific business address, but it can also be attached to a product that is sold across multiple locations.

This required a robust resolution strategy. We don't just check a single column; we traverse a hierarchy. We aggregate coordinates from the specific BusinessAddress, but if the review targets a product, we fetch all business addresses stocking that product. Furthermore, we resolve user locations not just from GPS pings (lat/lng), but also from Zipcode and City-level data provided in their profile.

// HigherCrudServiceReview.cs

// ...

var reviewsLatitudesLongitudes = await PairReviewsWithTheirUniqueLatsAndLngs(reviews);

var latitudesAndLongitudesOfUser = await PairLatitudesAndLongitudesOfUser(user!.Id);

// ...

Enter fullscreen mode Exit fullscreen mode

// HigherCrudServiceReview.cs

private double? CalculateClosestProximity(double lat, double lng, HashSet<(double, double)> latitudesLongitudes)
{
    if (latitudesLongitudes.Count == 0)
    {
        return null;
    }

    var absLat = Math.Abs(lat);
    var absLng = Math.Abs(lng);

    var proximity = double.MaxValue;

    foreach (var latitudeLongitude in latitudesLongitudes)
    {
        var latDiffAbs = Math.Abs(absLat - Math.Abs(latitudeLongitude.Item1));
        var lngDiffAbs = Math.Abs(absLng - Math.Abs(latitudeLongitude.Item2));

        var proximityOfTuple = Math.Abs(latDiffAbs - lngDiffAbs);

        if (proximityOfTuple < proximity)
        {
            proximity = proximityOfTuple;
        }
    }

    return proximity;
}

Enter fullscreen mode Exit fullscreen mode

This logic ensures that when we calculate proximity, we are matching a user's "area of influence" against a review's "area of availability".


The ML Core: Matrix Factorization on Implicit Feedback

For authenticated users, simple sorting isn't enough. We need personalization. I opted for a collaborative filtering approach using Matrix Factorization, but with a twist: we don't have explicit ratings (1-5 stars) for the act of viewing a review. Instead, we rely on Implicit Feedback - specifically, "Time Spent".

When a user stares at a review for 10, 30, or 60 seconds, that is a signal. We treat this duration as the label for the interaction.

Model Training Pipeline

The model is built using Microsoft.ML. The pipeline is relatively standard but effective. We map the UserId and ReviewId to keys and feed the Label (time spent in seconds) into a MatrixFactorizationTrainer.

// ReviewModel.cs

var estimator = mlContext.Transforms.Conversion.MapValueToKey("UserIdEncoded", "UserId")
    .Append(mlContext.Transforms.Conversion.MapValueToKey("ReviewIdEncoded", "ReviewId"));

var options = new MatrixFactorizationTrainer.Options
{
    MatrixColumnIndexColumnName = "UserIdEncoded",
    MatrixRowIndexColumnName = "ReviewIdEncoded",
    LabelColumnName = "Label",
    NumberOfIterations = 20,
    ApproximationRank = 100
};

Enter fullscreen mode Exit fullscreen mode

We set the ApproximationRank to 100 and run for 20 iterations. This balances latency and the ability to capture complex user-item interactions. Although implicit feedback data can be noisy, we train the model to predict how long a user would spend on a review they haven't seen yet, relying on the algorithm to find signal amidst the noise.

Operationalizing the Model: Retraining Strategy

A model is only as good as its data. Retraining a model on every single interaction is a resource drain. To solve this, I implemented a threshold-based retraining trigger.

We maintain a counter for specific activity types (staring at reviews). The model retrains only when the count of new activities hits a specific threshold (e.g., every x new interaction signals from a user). This ensures the model adapts to new trends without crippling the database with constant training jobs.

// HigherCrudServiceActivity.cs

public async Task<DtoPlainActivity> Insert(InsertDtoActivity insert, User user)
{
    // ...

    if (insert.ActivityTypeId is
        (short) EnumActivityType.STARING_AT_REVIEW_FOR_10_SECONDS or
        (short) EnumActivityType.STARING_AT_REVIEW_FOR_30_SECONDS or
        (short) EnumActivityType.STARING_AT_REVIEW_FOR_60_SECONDS
       )
    {
        await TrainReviewModelIfThresholdAchieved(user);
    }
}

private async Task TrainReviewModelIfThresholdAchieved(User user)
{
    var reviewActivitiesOfUserCount = await GetQueryable()
        .Where(a => a.UserId == user.Id &&
                    (a.ActivityTypeId == (short) EnumActivityType.STARING_AT_REVIEW_FOR_10_SECONDS ||
                    a.ActivityTypeId == (short) EnumActivityType.STARING_AT_REVIEW_FOR_30_SECONDS ||
                    a.ActivityTypeId == (short) EnumActivityType.STARING_AT_REVIEW_FOR_60_SECONDS)
              )
        .LongCountAsync();

    if (reviewActivitiesOfUserCount > 1 && reviewActivitiesOfUserCount % THRESHOLD_FOR_REVIEW_MODEL_TRAINING != 0)
    {
        return;
    }

    var reviewActivities = await GetQueryable()
        .Where(a => a.ActivityTypeId == (short) EnumActivityType.STARING_AT_REVIEW_FOR_10_SECONDS ||
                    a.ActivityTypeId == (short) EnumActivityType.STARING_AT_REVIEW_FOR_30_SECONDS ||
                    a.ActivityTypeId == (short) EnumActivityType.STARING_AT_REVIEW_FOR_60_SECONDS)
        .ToListAsync();

    ReviewModel.OrchestrateReviewRecommenderModel(reviewActivities, _webHostEnvironment, reviewActivities.LongCount());
}

Enter fullscreen mode Exit fullscreen mode


The "Buffer" Optimization & Popularity Dynamics

One of the more interesting engineering challenges was pagination. Standard pagination (Skip(x).Take(y)) breaks down when you have a volatile sorting order influenced by ML predictions and volatile proximity.

To solve this, I implemented a Buffer Strategy. Instead of querying the exact page size from the database, we fetch a larger "buffer" (e.g., 100 records) based on a stable initial sort (creation date). We then apply the heavy lifting - ML predictions, proximity calculations, and category matching - in-memory on this buffer.

// HigherCrudServiceReview.cs

// ...

var paginationCreator = new PaginationCreator<BaseSearchDto>(search, uriBuilder, totalRecords);

var bufferPage = paginationCreator.CalcSkippingRecordsCount() / REVIEW_BUFFER_SIZE;

query = query.Skip(bufferPage * REVIEW_BUFFER_SIZE).Take(REVIEW_BUFFER_SIZE);

var reviews = await query.ToListAsync();

// ...

Enter fullscreen mode Exit fullscreen mode

Crucially, this buffer approach mitigates a common pitfall of popularity-based ranking: the "rich get richer" feedback loop. If we ranked the entire database solely by total time spent, legacy reviews would dominate the feed indefinitely, burying new content.

By anchoring the buffer to CreatedAt, we enforce a sliding window of relevance. As new reviews are created, they enter the buffer, and older reviews are naturally pushed out. This ensures that "popularity" is only a deciding factor among recent content, guaranteeing freshness while still surfacing the best of what's new. It keeps the feed from stagnating and ensures that popularity serves as a quality signal for new content, rather than a permanent high ground for the old.


The Ranking Hierarchy

Finally, how do we merge all these signals? For a logged-in user, the sorting priority is strict:

  1. Prediction Score: A personalized prediction of how long the user will spend on the review.
  2. Proximity: How close is the user to the review's location?
  3. Category Matching: Does the review match the user's explicit interests?
  4. Global Popularity: Total time spent by all users on this review.
  5. Recency: Fallback to creation date.

Conclusion

Building the recommendation engine for Claprec was an exercise in balancing complexity with performance. By offloading geo-spatial resolution to helper methods, utilizing a buffer for pagination, and implementing an implicit-feedback Matrix Factorization model, I've created a system is created that feels instant yet deeply personalized.

It's a constant iteration - tuning the weights, adjusting the retraining threshold, and refining how we define "time spent". But for now, it provides a solid technical foundation for the user experience at claprec.dev.


What's Next?

While the recommendation engine serves as the "brain" of the platform, it relies on a robust data skeleton to function. In the next post, Claprec: Database Design - Modeling the Data (5/6), I'll peel back the layers on the storage architecture. I will share the full ER diagram for the project and detail the Entity Framework Core configurations that bring it to life. We'll look at how I modeled the relational database to empower the ML components - designing a schema that ensures data integrity and provides the flexibility needed to feed our algorithms effectively.


I'd love to hear your thoughts on this approach to recommendation systems or answer any questions you might have in the comments below.