<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Monem Benjeddou on Medium]]></title>
        <description><![CDATA[Stories by Monem Benjeddou on Medium]]></description>
        <link>https://medium.com/@Monem_Benjeddou?source=rss-f0e9b44f6996------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-FoGFCe59y2izBuHlKJwog.jpeg</url>
            <title>Stories by Monem Benjeddou on Medium</title>
            <link>https://medium.com/@Monem_Benjeddou?source=rss-f0e9b44f6996------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:03:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Monem_Benjeddou/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I Kept Rebuilding the Same AI Agent Foundation. So I Built It Once.]]></title>
            <link>https://medium.com/@Monem_Benjeddou/i-kept-rebuilding-the-same-ai-agent-foundation-so-i-built-it-once-350cedc4a95c?source=rss-f0e9b44f6996------2</link>
            <guid isPermaLink="false">https://medium.com/p/350cedc4a95c</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-foundry]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Monem Benjeddou]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 12:33:49 GMT</pubDate>
            <atom:updated>2026-10-21T12:33:49.500Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What I learned turning a pile of agent prototypes into one open-source starter for Azure, including the parts that went wrong.</em></p><p>I counted recently. In the last year I have written the same code at least five times.</p><p>A client wrapper around Azure OpenAI. A loop that calls the model, runs a tool, and calls the model again. Some glue to search an index. A FastAPI route on top. Every project started with days of that plumbing before anyone touched the actual problem.</p><p>And every time, the plumbing was a little different, a little worse tested, and tied a little tighter to whatever SDK version was current that month.</p><p>So I stopped. I took everything I kept rebuilding and turned it into one starter, built properly, once. It’s called <a href="https://github.com/Monem-Benjeddou/azure-agents-starter">Azure Agents Starter</a> and it’s open source.</p><p>This is the story of building it, and the handful of things that surprised me along the way.</p><h3>Why agent prototypes die in production</h3><p>A demo agent is easy. You can get one answering questions in an afternoon. The trouble starts when someone says “great, let’s ship it.” In my experience, three things break, almost every time.</p><p><strong>The business logic is welded to one vendor.</strong> The OpenAI client is imported in the same file that decides what the agent should do. Then the team wants to try a different model, or move the agents to a managed service, and suddenly it’s a rewrite.</p><p><strong>One chat loop pretends to be a system.</strong> Real work needs more than one agent answering one question. You need a researcher that looks things up, a writer that drafts, maybe a reviewer that checks the draft. A single loop doesn’t scale to that, and bolting it on later gets messy fast.</p><p><strong>Nothing runs without the cloud.</strong> If every test needs live credentials, people stop writing tests. I’ve seen it on every team I’ve worked with, and I’ve done it myself.</p><p>I wanted a foundation that fixed all three by design, not by discipline.</p><h3>The boring idea that does most of the work</h3><p>The fix for the first problem is old and unglamorous: <a href="https://alistair.cockburn.us/hexagonal-architecture/">hexagonal architecture</a>, also called ports and adapters.</p><p>The core of the app only talks to interfaces. It never imports Azure, never imports OpenAI. Here is the entire contract for a chat model:</p><pre>class ChatModel(Protocol):<br>    async def complete(<br>        self,<br>        messages: Sequence[Message],<br>        tools: Sequence[Tool] = (),<br>        on_token: Callable[[str], None] | None = None,<br>    ) -&gt; Message:<br>        &quot;&quot;&quot;Return the assistant&#39;s next message. With `on_token`, text is streamed as it arrives.&quot;&quot;&quot;</pre><p>There are four of these ports: ChatModel, Embedder, VectorIndex and AgentRuntime. Adapters implement them: one for Azure OpenAI, one for Azure AI Search, one for Azure AI Foundry, and so on. A single file, container.py, decides which adapter plugs into which port.</p><p>[embed: node/e3020c45–4f2d]</p><p>Arrows point inward: the HTTP API and CLI call the core, and each adapter implements one of its ports.</p><p>That sounds like ceremony until you feel the payoff. The same adapter that talks to Azure OpenAI also talks to Ollama on my laptop, because both speak the OpenAI API. And because the core only knows about interfaces, all 50 tests run with fakes. No credentials, no network, under a second. That’s the third problem gone.</p><h3>Six ways agents can work together</h3><p>For the second problem, I didn’t want to invent my own vocabulary. Microsoft already documents the main <a href="https://learn.microsoft.com/azure/architecture/ai-ml/guide/ai-agent-design-patterns">orchestration patterns</a>, so I used their names instead of inventing my own: five from the docs, plus agents-as-tools, the supervisor pattern I reach for most.</p><p><strong>Agents as tools.</strong> A lead agent asks specialists for help, then writes the reply. Use it when one agent must own the answer.</p><p><strong>Sequential.</strong> Agents work one after another: research, write, review. Use it when the steps are known upfront.</p><p><strong>Concurrent.</strong> Agents work at the same time and an aggregator combines their answers. Use it when you want independent views, or speed.</p><p><strong>Handoff.</strong> A front-desk agent passes the whole conversation to a specialist. Use it for routing to the right expert.</p><p><strong>Group chat.</strong> A manager picks who speaks next in a shared conversation. Use it for drafting and reviewing in rounds.</p><p><strong>Magentic.</strong> A manager plans, hands out steps, tracks progress and replans. Use it for open-ended tasks where the steps aren’t known.</p><p>Every agent is declared once, as plain data:</p><pre>RESEARCHER = AgentSpec(<br>    name=&quot;researcher&quot;,<br>    description=&quot;Answers questions from the internal knowledge base, with citations.&quot;,<br>    instructions=&quot;Search the knowledge base before answering. ...&quot;,<br>    tools=(SEARCH_TOOL_NAME,),<br>)</pre><p>Then a workflow is one line: Sequential(runtime, (&quot;researcher&quot;, &quot;writer&quot;, &quot;reviewer&quot;)).</p><p>Here’s the part I didn’t expect. When I first ran the group chat against real data, it confidently listed meetings that didn’t exist. Nice titles, plausible details, completely invented. The cause was embarrassingly simple: the chat had a writer and a reviewer, but nobody who could actually search. The writer filled the silence. Adding the researcher to the group, and telling the writer to say “research is needed” when it has nothing to work from, fixed it. Patterns don’t make agents honest. The team you put in them does.</p><h3>One catalog, two runtimes, and a near-miss</h3><p>Some teams want agents running inside their own app. Others want them hosted on <a href="https://learn.microsoft.com/azure/ai-foundry/agents/overview">Azure AI Foundry Agent Service</a>, where threads and runs live on Azure’s side. I didn’t want to pick for them.</p><p>So AgentRuntime is a port too. The local runtime runs a tool-calling loop in-process. The Foundry runtime creates a thread, starts a run, answers tool calls when the run asks for them, and reads back the result. Same agents, same workflows. You switch with one setting: AGENT_RUNTIME=foundry.</p><p>The mapping is mostly natural. An agent that delegates to sub-agents becomes a <a href="https://learn.microsoft.com/azure/ai-foundry/agents/how-to/connected-agents">connected agent</a> in Foundry. Search becomes Foundry’s built-in Azure AI Search tool. Handoff has no Foundry equivalent, so those agents are skipped, and the docs say so.</p><p>Now the near-miss. My first provisioning command matched agents by name: if an agent called triage already existed, update it. Clean and idempotent, I thought.</p><p>Then I pointed it at a real, shared Foundry project. It had well over a hundred agents in it, several literally named test. Matching by name would have been slow, and worse, it could have quietly overwritten another team&#39;s agent that happened to share a name.</p><p>I rewrote it before creating anything. Provisioning now only updates agent IDs it created itself, and prefixes every name so they’re easy to spot. It’s a small change, but it’s the difference between a tool people trust in a shared environment and one they ban.</p><h3>Watching agents think, live</h3><p>Multi-agent runs are slow. A supervisor asks a researcher, the researcher searches, then writes, then the supervisor writes. Staring at a spinner for twenty seconds is a terrible experience, and it hides what’s going on.</p><p>So every workflow streams over <a href="https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events">Server-Sent Events</a>. You see each step as it happens, then the answer word by word:</p><pre>event: trace<br>data: {&quot;agent&quot;: &quot;triage&quot;, &quot;kind&quot;: &quot;delegation&quot;, &quot;detail&quot;: &quot;ask_researcher&quot;}</pre><pre>event: token<br>data: {&quot;agent&quot;: &quot;researcher&quot;, &quot;text&quot;: &quot;Hotel costs are reimbursed&quot;}</pre><pre>event: result<br>data: {&quot;answer&quot;: &quot;...&quot;, &quot;trace&quot;: [...]}</pre><p>The interesting problem was plumbing. Events come from deep inside a runtime, sometimes from agents running in parallel. I didn’t want to thread a callback through every function signature in the codebase.</p><p>Python’s <a href="https://docs.python.org/3/library/contextvars.html">contextvars</a> solved it in about thirty lines. The stream sets a listener in a ContextVar, and anything running inside that context can publish to it:</p><pre>_listener: ContextVar[Listener | None] = ContextVar(&quot;agents_starter_listener&quot;, default=None)</pre><pre>def record(trace: list[TraceEvent], event: TraceEvent) -&gt; None:<br>    trace.append(event)<br>    listener = _listener.get()<br>    if listener is not None:<br>        listener(event)</pre><p>The nice surprise: tasks created by asyncio.gather copy the current context. So when two agents run concurrently, both stream into the same response without any extra wiring. It&#39;s the same trick OpenTelemetry uses to carry trace context around.</p><h3>What I’d tell myself before starting</h3><p><strong>Send tool errors back to the model.</strong> Smaller models often produce broken JSON for tool arguments, or call a tool that doesn’t exist. My first instinct was to fail the request. Feeding the error back as a tool message works much better: the model reads “missing required arguments [‘query’]” and gets a chance to fix itself on the next turn.</p><p><strong>Small local models need blunt instructions.</strong> With a 4B model on my laptop, the supervisor kept answering on its own and inventing a citation, instead of asking the researcher. Rewriting its instructions to “you have no knowledge of your own” fixed it. Bigger models forgive vague prompts; the smallest one you plan to support won’t. Test with that one.</p><p><strong>Treat other people’s data as read-only.</strong> When I tried to create a search index on a real Azure AI Search service, it failed: the service had hit its 50-index limit. That pushed me to add a mode that searches an existing index without ever writing to it. It turned out to be one of the most useful features, because most teams already have indexes they don’t want touched.</p><p><strong>Hosted services have their own pace.</strong> On a busy Foundry project, starting a single run once took more than four minutes. Design for slow upstreams: timeouts that cancel the run, and threads that get cleaned up even when things fail.</p><p><strong>Fail at startup, not mid-conversation.</strong> An agent that references a tool that doesn’t exist, or two agents that delegate to each other in a loop, should crash the app on boot. Finding that out from a confused user is much worse.</p><h3>Try it in ten minutes</h3><p>You don’t need an Azure account to start. With Python 3.10+ and <a href="https://ollama.com/">Ollama</a>:</p><pre>git clone https://github.com/Monem-Benjeddou/azure-agents-starter.git<br>cd azure-agents-starter<br>pip install -e &quot;.[dev]&quot;<br>ollama pull qwen3:4b &amp;&amp; ollama pull nomic-embed-text<br>cp .env.example .env</pre><p>Set four lines in .env so it talks to Ollama:</p><pre>LLM_PROVIDER=openai_compatible<br>CHAT_MODEL=qwen3:4b<br>EMBEDDING_MODEL=nomic-embed-text<br>EMBEDDING_DIMENSIONS=768</pre><p>Then load the sample documents and ask something:</p><pre>agents-starter ingest examples/knowledge<br>agents-starter chat &quot;How much can I spend on a hotel?&quot; --stream</pre><p>When you’re ready for Azure, point the same app at your Azure OpenAI deployment, add Azure AI Search, or move the agents to Foundry. The code doesn’t change. Only the settings do.</p><h3>The point</h3><p>None of the individual pieces here are new. Ports and adapters is decades old. The orchestration patterns are documented by Microsoft. Streaming is a web standard.</p><p>What was missing, for me, was having them together, tested, and boring enough to trust, so the next project can start on day one with the actual problem instead of the plumbing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gIPtmWwuufr_Bd79wfRiZQ.png" /><figcaption>Reference architecture</figcaption></figure><p>If that’s useful to you, the code is MIT-licensed on <a href="https://github.com/Monem-Benjeddou/azure-agents-starter">GitHub</a>. I’d genuinely like to hear what breaks when you try it, and which pattern you end up using most.</p><p>#Azure #AIAgents #MultiAgent #SoftwareArchitecture #Python #OpenSource #AzureAI #LLM</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=350cedc4a95c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatic HTTPS in ASP.NET Core, without certbot]]></title>
            <link>https://medium.com/@Monem_Benjeddou/automatic-https-in-asp-net-core-without-certbot-24795dbe9cfb?source=rss-f0e9b44f6996------2</link>
            <guid isPermaLink="false">https://medium.com/p/24795dbe9cfb</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[kestrel]]></category>
            <category><![CDATA[lets-encrypt]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Monem Benjeddou]]></dc:creator>
            <pubDate>Wed, 14 Oct 2026 14:30:26 GMT</pubDate>
            <atom:updated>2026-10-14T14:30:26.538Z</atom:updated>
            <content:encoded><![CDATA[<h3>It’s 3 AM. Your phone lights up: <em>“Your connection is not private.”</em></h3><p>The certificate expired. It renewed fine last time. But someone rebuilt the server, the cron job didn’t come back, and nobody noticed.</p><p>And it’s about to get worse. In 2025 the CA/Browser Forum <a href="https://cabforum.org/2025/04/11/ballot-sc081v3-introduce-schedule-of-reducing-validity-and-data-reuse-periods/">voted to cut certificate lifetimes step by step down to 47 days by 2029</a>, and Let’s Encrypt already offers optional <a href="https://letsencrypt.org/2025/01/16/6-day-and-ip-certs/">6-day certificates</a>. At that pace, renewing by hand isn’t a chore anymore. It’s a job. And a renewal script running next to your app is one more thing that can quietly break.</p><p>So I built KestrelAcme.</p><p>Think of it as a certificate team that lives inside your app. And when you run three copies of the app, they agree on who does the work.</p><h3>Three lines, and you’re done</h3><pre>builder.Services.AddKestrelAcme(o =&gt;<br>{<br>    o.Domains.Add(&quot;example.com&quot;);<br>    o.Email = &quot;you@example.com&quot;;<br>    o.AcceptTermsOfService = true;<br>});</pre><p>When the app starts, it gets a certificate from Let’s Encrypt and hands it to Kestrel. When renewal time comes, it gets a new one. New TLS connections use it right away; open connections finish on the old one. No restart, no certbot.</p><p>That was the easy part.</p><h3>Problem one: a question .NET won’t let you hear</h3><p>Let’s Encrypt has to check you really own the domain. HTTP-01 does it on port 80, but plenty of servers don’t want port 80 open at all.</p><p>TLS-ALPN-01 does it on port 443. During the handshake, Let’s Encrypt says <em>“I’m speaking </em><em>acme-tls/1&quot;</em>, and your server has to answer with a special one-off certificate. That means you need the client&#39;s protocol list before choosing a certificate, and Kestrel doesn&#39;t give you that at that moment.</p><p>So KestrelAcme peeks. A small connection middleware reads the first TLS message (the ClientHello) without consuming it, notes the server name and the protocols, and lets TLS run as normal. By the time Kestrel asks “which certificate?”, the answer is already there.</p><h3>Problem two: Kubernetes, in human terms</h3><p>Then someone asked the question I’d been avoiding:</p><blockquote>“What about Kubernetes? I have three replicas. Which one renews?”</blockquote><p>Honest answer: all of them. Each pod would order its own certificate, and Let’s Encrypt allows only 5 duplicate certificates per week. Ten pods would burn that in a day.</p><p>It gets worse. Let’s Encrypt doesn’t check from one place. It checks from several locations at once, and your load balancer sends each check to whichever pod it likes. Pod A orders, pod C gets the check, pod C has no idea what to say. I tested it:</p><pre>Validation failed: ... returned 404<br>Certificate issuance failed (1 in a row); retrying in 00:05:00.</pre><p>Forever.</p><h3>One pod orders, the others wait</h3><p>A lock decides who orders. Everyone else waits, then loads the new certificate from shared storage, with no restart. Three details made all the difference:</p><ul><li>Keep the lock through retries. Otherwise the next pod jumps in, fails too, and you burn rate limits in parallel.</li><li>Look again after taking the lock. Another pod may have just finished.</li><li>Don’t let go until the certificate is saved. Otherwise someone orders a duplicate.</li></ul><h3>Any pod can answer</h3><p>The pod that orders writes its challenge answers to shared storage, then waits two seconds before asking Let’s Encrypt to check. Every other pod reads those answers and replies from memory, at most one read per second, because anyone on the internet can send fake challenge requests.</p><h3>No Redis, no client library</h3><p>On a shared volume (NFS, Azure Files, EFS), the lock is just a file lock. If a pod dies, the OS frees it.</p><p>On Kubernetes, it uses a Lease (the same thing Kubernetes uses for leader election) and keeps certificates in Secrets. Every pod already has a token and the cluster’s CA mounted, and the API is plain HTTP, so there’s no client library involved. The package has no external NuGet dependencies.</p><p>One trap: node clocks don’t agree, so you can’t trust the timestamp in a lease. Each pod waits for the lease to stop changing for the full duration <em>by its own clock</em>. That’s the same trick Kubernetes’ own controllers use. And the holder gives up after 40 seconds without renewing, while others can only take over after 60. Even in a network split, two pods never order at once.</p><h3>The parts that caught me off guard</h3><p>I assumed the pod that ordered would be the one Let’s Encrypt talked to. It usually isn’t, and that one wrong assumption shaped most of the design.</p><p>Errors were the next trap. When storage couldn’t be read, the first version took it as “no certificate yet” and happily ordered a new one. Now it backs off and tries later.</p><p>Then there’s the internet itself. Anyone can send a fake challenge request, so every lookup it can trigger has a limit, and the challenge certificate is built once, not on every connection.</p><p>To trust the tests, I broke each fix on purpose and made sure a test went red. One didn’t. It counted DNS records to spot duplicate orders, but Let’s Encrypt reuses authorizations, so a duplicate slipped through without a new record. It counts orders in the logs now. The same habit caught a cache that silently stopped refreshing forever.</p><p>And no local test showed what the real cluster did.</p><h3>Then I tried it for real</h3><p>An AKS cluster, three replicas behind a public load balancer, Let’s Encrypt staging, all pods starting at the same moment with no certificate:</p><pre>pod A   Ordering a certificate using tls-alpn-01.<br>pod B   Another instance is ordering the certificate; looking again in 00:00:30.<br>pod C   Another instance is ordering the certificate; looking again in 00:00:30.<br>pod B   Serving the TLS-ALPN-01 challenge certificate.<br>pod B   Serving the TLS-ALPN-01 challenge certificate.<br>pod B   Serving the TLS-ALPN-01 challenge certificate.<br>pod A   validated with tls-alpn-01.<br>pod A   Certificate issued (took 00:00:13.35).<br>pod B   Loaded the stored certificate.<br>pod C   Loaded the stored certificate.</pre><p><strong>One order.</strong> Let’s Encrypt’s checks landed on pod B, which wasn’t even ordering, and it answered all three. Thirty seconds later, all three pods served the same certificate. I killed one; its replacement loaded the stored certificate without ordering anything.</p><p>This isn’t some academic project. We run it in production.</p><h3>Before you use it</h3><ul><li>Kestrel has to receive HTTPS itself. If nginx or a load balancer terminates TLS, you don’t need this.</li><li>On Kubernetes, use a LoadBalancer Service or a TCP passthrough ingress.</li><li>Kubernetes Secrets are only base64 unless encryption at rest is on, so give the app its own namespace.</li><li>Wildcards need DNS-01. The README has a Cloudflare example.</li></ul><h3>Bottom line</h3><p>KestrelAcme treats certificates as part of the app, not a job next to it. One pod orders, every pod can answer, and nobody restarts.</p><p>On paper: 3 challenge types, 3 replicas, 1 order, 0 restarts, 0 external dependencies. In practice: no more 3 AM phone calls.</p><h3>Try it yourself!</h3><pre>dotnet add package KestrelAcme</pre><p>MIT licensed, .NET 8 and 10, Windows, Linux and macOS, Native AOT.</p><p>👉 <a href="https://github.com/Monem-Benjeddou/KestrelAcme">github.com/Monem-Benjeddou/KestrelAcme</a></p><p>Running Kestrel at the edge? Got a certificate war story? Drop it in the comments, I’d love to hear it. Hit a snag? Open an issue, I read every one. And if it saves you a 3 AM call, a ⭐ helps others find it. 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4fsm8LbgXR3sO66C5Rd0_w.png" /><figcaption>KestrelAcme</figcaption></figure><h3>dotnet #aspnetcore #kestrel #kubernetes #letsencrypt #acme #opensource #csharp #devops #cloudnative</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24795dbe9cfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AEGIS: A PII Firewall Built for Arabic Text (Because Most NLP Tools Aren’t)]]></title>
            <link>https://medium.com/@Monem_Benjeddou/aegis-a-pii-firewall-built-for-arabic-text-because-most-nlp-tools-arent-eb8dd278c12c?source=rss-f0e9b44f6996------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb8dd278c12c</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[pii]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Monem Benjeddou]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 14:01:21 GMT</pubDate>
            <atom:updated>2026-06-30T14:01:21.532Z</atom:updated>
            <content:encoded><![CDATA[<p>Arabic NLP is a different beast from English NLP, and most off-the-shelf PII tools quietly assume you’re working in English. Right-to-left script, four-ish regional dialects that don’t always understand each other, inconsistent diacritics, and a name like “السيده” that a generic model will happily mistag as an organization — none of that is covered by bolting a multilingual flag onto a Western pipeline.</p><p>I needed something that could actually catch PII in Arabic documents before they ever touched an LLM, and “mostly works” wasn’t an option — a missed name or a leaked ID number isn’t a bug, it’s a compliance incident. So I built <strong>AEGIS</strong>.</p><p><strong>AEGIS</strong> — <em>Adaptive Entity Guard for Inference Safety</em> — is a multi-stage PII detection pipeline built for Arabic text. It sits between raw documents and any LLM, finding sensitive data, merging results from five specialized detectors, and masking what shouldn’t cross the line.</p><p>Think of it as a bouncer with five different ID scanners and one strict dress code.</p><h3>The problem, in human terms</h3><p>When someone uploads an Arabic enrollment form, a support email, or an HTML export, they’re not sending “a document.” They’re sending a bundle of identities.</p><p>Here’s what leaked in one real test document (tc001):</p><ul><li>Full person names — 2</li><li>Email addresses — 2</li><li>Phone numbers — 2</li><li>Dates of birth / expiry — 3</li><li>URLs — 1</li><li>Locations — 3</li><li>Organizations — 1</li><li><strong>Total sensitive spans — 14</strong></li></ul><p>That’s <strong>14 separate pieces of personal data</strong> in a single paragraph — before the LLM has written a single token.</p><p>Across the full golden test suite (9 scenarios), the system is expected to catch <strong>38 sensitive spans</strong>: roughly <strong>18 structured</strong> (emails, phones, IBANs, dates, URLs) and <strong>20 semantic</strong> (names, places, organizations).</p><p>Without a gate like AEGIS, all 38 ride straight into model context — training risk, compliance exposure, and the chance the model parrots someone’s phone number back in a reply.</p><h3>Architecture at a glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7QbNn0qDQNmfYUwlvuA_sg.png" /><figcaption><strong>AEGIS Pipeline Architecture</strong></figcaption></figure><p>The pipeline has six named layers. Each does one job well.</p><h3>1. DECANT — strip the noise first</h3><p>Raw input is rarely clean. Emails arrive as HTML. Attachments hide inside Base64 blobs. Arabic text has inconsistent whitespace.</p><p><strong>DECANT</strong> (Document Extraction, Cleaning &amp; Normalization Toolkit) handles this before any model runs:</p><ul><li>Strips HTML tags and decodes entities</li><li>Pulls Base64-encoded attachments out of the text</li><li>Normalizes whitespace for consistent detection</li></ul><p>If you skip this step, PII can hide inside &lt;span&gt; tags or encoded blobs that regex never sees.</p><h3>2. IRONCLAD — structured PII (the hard facts)</h3><p><strong>IRONCLAD</strong> is Presidio + GLiNER. It owns anything with a predictable shape:</p><ul><li>Emails, phone numbers, IBANs, credit cards</li><li>Dates, URLs, IP addresses</li><li>Passports, SSNs, driver licenses, bank accounts</li></ul><p>That’s <strong>11 structured entity types</strong>. These are the “this is definitely sensitive” hits — not guesses about whether a word is a person’s name.</p><p>GLiNER adds zero-shot NER on top of Presidio’s regex and spaCy recognizers, so you catch entity types you didn’t train for.</p><h3>3. ORACLE CASCADE — Arabic semantic intelligence</h3><p>Arabic names, organizations, and locations don’t follow regex patterns. Four models run in a priority waterfall:</p><ul><li><strong>Priority 4 (king): AraBERTv2</strong> — primary authority for PERSON, ORG, LOCATION</li><li><strong>Priority 3: CAMeL Tools</strong> — secondary, strong on classical Arabic NER</li><li><strong>Priority 2: Arabic NER ACE</strong> — tertiary fallback</li><li><strong>Priority 1: SinaTools</strong> — fourth, optional, graceful if models aren’t installed</li></ul><p>All four hunt the same <strong>3 semantic types</strong>: PERSON, ORGANIZATION, LOCATION.</p><p>They don’t vote democratically. When two models flag the same text span, the higher-priority model wins. If they’re tied on priority, higher confidence wins.</p><h3>4. CONSENSUS ENGINE — merge without chaos</h3><p>Five detectors firing on the same paragraph will disagree. Overlapping spans, duplicate hits, false positives on Arabic titles like “السيده” (Mrs.) — it’s messy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WG5w5SKmA51Jib53OYJSoQ.png" /><figcaption>Consensus Engine Fusion</figcaption></figure><p>The <strong>CONSENSUS ENGINE</strong> (EntityMerger) applies clear rules:</p><ul><li><strong>Semantic entities</strong> → ORACLE CASCADE priority wins</li><li><strong>Structured entities</strong> → IRONCLAD always wins over semantic guesses</li><li><strong>Overlapping structured hits</strong> → keep the longer, more complete span</li><li><strong>False positive filter</strong> → drop Arabic titles, pronouns, and numeric strings mislabeled as organizations</li></ul><p>The output is a clean, deduplicated, sorted list of entities with positions, confidence scores, and source attribution.</p><h3>5. VEIL — mask before the model sees anything</h3><p>Detection alone isn’t enough. You need a safe version of the text.</p><p><strong>VEIL</strong> applies one of four masking strategies:</p><ul><li><strong>Asterisk</strong> (default): fatima.hassan87@email.com → **************************</li><li><strong>Redaction</strong>: [EMAIL] placeholder tags</li><li><strong>Partial</strong>: show first/last chars, e.g. fa*************om</li><li><strong>Hash</strong>: deterministic 8-char MD5 slice</li></ul><p>Masking runs <strong>back-to-front</strong> through the text so character positions stay stable when multiple entities overlap.</p><h3>6. LLM GATE — only clean text gets through</h3><p>The sanitized document — with PII stripped or replaced — is what finally enters your LLM prompt. The original never has to.</p><h3>The journey, step by step</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4jVctNWwuNXmsuwfEcz-Hw.png" /><figcaption><strong>Document Journey Sequence</strong></figcaption></figure><pre>Raw document<br>   ↓<br>DECANT (clean + normalize)<br>   ↓<br>   ├── IRONCLAD (structured PII) ──┐<br>   └── ORACLE CASCADE (semantic) ──┤<br>   ↓<br>   CONSENSUS ENGINE<br>   ↓<br>   VEIL (mask)<br>   ↓<br>   LLM GATE ✓</pre><h3>GATEHOUSE — the API front door</h3><p>The pipeline is wrapped in <strong>GATEHOUSE</strong>, a FastAPI service that exposes:</p><ul><li>POST /detect-pii — detect entities in a single text</li><li>Batch endpoints for processing many documents in parallel</li><li>Configurable <strong>confidence threshold</strong> (default: 0.5 — entities below 50% confidence are dropped)</li><li>Label filtering — only return the entity types you care about</li></ul><p>A typical response includes:</p><ul><li><strong>Entity count</strong> — how many spans were found</li><li><strong>Processing time</strong> — detection latency in seconds (logged to 4 decimal places)</li><li><strong>Per-entity metadata</strong> — type, value, position, confidence, source model, unique ID</li></ul><p>Docker Compose deployment mounts model volumes so HuggingFace weights persist across restarts. GPU acceleration (CUDA/MPS) is auto-detected.</p><h3>Why this is useful — the numbers that matter</h3><h3>Compliance and risk</h3><p>Every entity the pipeline catches is one fewer piece of PII in your LLM’s context window. On tc001 alone, that’s <strong>14 spans</strong> — two full identities with contact info, financial details, and location data — that never reach the model.</p><h3>Arabic is hard; one model isn’t enough</h3><p>A single English-centric NER model will miss Arabic names, confuse titles with persons, and treat national ID numbers as organization names. The ORACLE CASCADE exists because <strong>no single Arabic model wins on every text style</strong> — dialect, diacritics, transliteration, and mixed Arabic-English content all behave differently.</p><p>Running four models with a priority merge gives you breadth without letting the lowest-quality detector override the best one.</p><h3>Graceful degradation</h3><p>If SinaTools isn’t installed, the pipeline warns you and continues. If CAMeL is unavailable, AraBERTv2 and Arabic NER ACE still run. The system is designed to <strong>degrade coverage, not crash</strong>.</p><h3>Throughput at scale</h3><p>detect_batch() parallelizes across documents using ThreadPoolExecutor (GPU-safe — models can&#39;t be pickled for multiprocessing). Auto-scales workers to min(document_count, CPU cores).</p><h3>Auditability</h3><p>Every entity gets a UUID, a source tag (presidio, arabertv2, camel, etc.), and a confidence score. When compliance asks &quot;why was this flagged?&quot;, you have an answer — not a black box.</p><h3>The naming cheat sheet</h3><ul><li><strong>Text preprocessing</strong> → DECANT — strip HTML, decode Base64, normalize</li><li><strong>Presidio + GLiNER</strong> → IRONCLAD — structured PII detection</li><li><strong>AraBERTv2 → SinaTools</strong> → ORACLE CASCADE — Arabic semantic NER waterfall</li><li><strong>EntityMerger</strong> → CONSENSUS ENGINE — merge, dedupe, resolve conflicts</li><li><strong>TextMasker</strong> → VEIL — mask/redact before LLM</li><li><strong>FastAPI service</strong> → GATEHOUSE — REST API entry point</li><li><strong>Full pipeline</strong> → AEGIS — end-to-end guard for inference safety</li></ul><h3>Bottom line</h3><p>AEGIS treats PII detection as a <strong>pipeline problem</strong>, not a single-model problem. DECANT cleans the input. IRONCLAD and ORACLE CASCADE hunt different kinds of sensitive data in parallel. CONSENSUS ENGINE picks winners when models disagree. VEIL ensures the LLM only sees sanitized text.</p><p>On paper: <strong>5 stages</strong>, <strong>5 detectors</strong>, <strong>14 entity categories</strong>, <strong>9 test scenarios</strong>, <strong>38 expected spans</strong> in the golden suite. In practice: your users’ names, emails, and phone numbers stay on your side of the wall — not in the model’s memory.<br>#ArabicNLP #PII #DataPrivacy #LLM #AIEngineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb8dd278c12c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ship AI Features Faster: Building a Reusable Azure Foundation for Your Team]]></title>
            <link>https://medium.com/@Monem_Benjeddou/ship-ai-features-faster-building-a-reusable-azure-foundation-for-your-team-83d8a7c68908?source=rss-f0e9b44f6996------2</link>
            <guid isPermaLink="false">https://medium.com/p/83d8a7c68908</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Monem Benjeddou]]></dc:creator>
            <pubDate>Wed, 03 Dec 2025 11:38:59 GMT</pubDate>
            <atom:updated>2025-12-03T11:38:59.036Z</atom:updated>
            <content:encoded><![CDATA[<p>It was 3 AM, and we were debugging our third production incident that week. The issue? An Azure OpenAI API key had expired, and it was hardcoded in seven different places across three services. We’d spent hours hunting down every reference, redeploying services, and crossing our fingers.</p><p>That night, we made a decision: never again.</p><p>If you’re building more than one AI feature be it RAG workflows, chatbots, or intelligent routers you know this pain. The quick, prototype-style code that gets the first demo working becomes a maintenance nightmare the moment you need to scale. Credentials are scattered, streaming is inconsistent, and swapping a model feels like rebuilding the engine mid-flight.</p><p>Over several weeks, we tore down our ad-hoc setup and built a shared Azure layer that now powers dozens of production AI agents. The goal was simple: let product teams ship AI features quickly, without each new feature multiplying our operational headaches.</p><p>This is the story of that architecture. If your roadmap has more than one AI module on it, the patterns below will save you from our 3 AM fate.</p><h3>From Chaos to Control: The Core Problems We Solved</h3><p>Our old approach followed a familiar, painful pattern: every new feature or service wrote its own direct calls to the Azure OpenAI SDK, configured its own search client, and implemented its own error handling. This led to three critical failures:</p><ol><li>Ad-Hoc Azure Calls Everywhere: Code duplication, inconsistent timeouts/retries, and no standard way to upgrade SDKs or change authentication.</li><li>Duplicated, Fragile Configuration: API endpoints and keys were hard-coded or sprinkled in .env files. Rotating a credential was a high-risk, multi-hour hunt.</li><li>No Consistent Story for Streaming: Each feature implemented its own chunking logic or WebSocket flow, forcing our frontend team to write new integration code every time.</li></ol><p>We didn’t just need a better library; we needed a new foundation</p><h3>Big Picture: How the System Is Structured</h3><p>At a high level, the system looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fpkXxdWS5OsXVoh2D0Cxvw.jpeg" /><figcaption>System Structure</figcaption></figure><ul><li>Feature modules (legal_document_rag, smart_router, hr_rag, etc.) implement business logic and APIs.</li><li>shared/* is a reusable Azure integration layer:</li><li>Central config (module.json, agents.json).</li><li>Connection‑pooled clients and adapters (OpenAI, AI Foundry, Search, Blob, Doc Intelligence, Whisper).</li><li>Generic agents and tools.</li><li>Standard streaming and WebSocket events.</li><li>Azure services are just the implementation detail behind the shared layer.</li></ul><p>The key idea: feature modules never talk directly to Azure SDKs. They express what they need through configuration and a small agent API, and the shared layer handles the rest.</p><h3>Our Design Principles: The “Non-Negotiables”</h3><p>To fix this, we established four core principles for our shared layer.</p><p>1. Configuration-Driven, Not Code-Driven<br>Every feature module declares its needs in simple JSON configs, not Python code. A central ConfigurationManager loads and validates these files, resolving secrets from the environment.</p><p>This means adding a new LLM or changing a model deployment is a config change, not a code change. Here’s a simplified view of our module.json:</p><pre>// config/module.json<br>{<br>  &quot;name&quot;: &quot;some_rag_name&quot;,<br>  &quot;adapters&quot;: {<br>    &quot;llm&quot;: {<br>      &quot;adapter&quot;: &quot;azure_openai&quot;,<br>      &quot;endpoint&quot;: &quot;${AZURE_OPENAI_ENDPOINT}&quot;,// Env vars resolved at startup<br>      &quot;api_version&quot;: &quot;2024-08-01-preview&quot;,<br>      &quot;chat_model&quot;: &quot;${AZURE_OPENAI_CHAT_DEPLOYMENT}&quot;,// Env vars resolved at startup<br>      &quot;auth&quot;: {<br>        &quot;type&quot;: &quot;api_key&quot;,<br>        &quot;api_key&quot;: &quot;${AZURE_OPENAI_API_KEY}&quot;<br>      }<br>    }<br>  }<br>}</pre><p>And in agents.json:</p><pre>// config/agents.json<br>{<br>  &quot;agents&quot;: [<br>    {<br>      &quot;id&quot;: &quot;some_agent_assistant&quot;,<br>      &quot;name&quot;: &quot;Agent Assistant&quot;,<br>      &quot;type&quot;: &quot;azure_ai_foundry&quot;,<br>      &quot;model&quot;: {<br>        &quot;name&quot;: &quot;gpt-4o-mini&quot;,<br>        &quot;temperature&quot;: 0.7,<br>        &quot;max_tokens&quot;: 2000<br>      },<br>      &quot;prompt&quot;: {<br>        &quot;file&quot;: &quot;prompts/legislator.prompty&quot;<br>      },<br>      &quot;dependencies&quot;: {<br>        &quot;llm&quot;: {<br>          &quot;adapter&quot;: &quot;azure_openai&quot;,<br>          &quot;config_ref&quot;: &quot;module.adapters.llm&quot;<br>        }<br>      }<br>    }<br>  ]<br>}</pre><p>Effect: Adding or changing an agent or adapter is mostly a config change, not a code change.</p><h4>2. Provider‑Agnostic Agents</h4><p>We strictly separate the <em>what</em> from the <em>how</em>.</p><ul><li>Adapters are low-level wrappers for Azure SDKs (OpenAI, Search, Blob Storage).</li><li>Agents are high-level interfaces that define behavior (chat(), stream_chat()).</li></ul><p>Feature modules only talk to the BaseAgent interface. Whether that agent uses raw Azure OpenAI or a full Azure AI Foundry workflow behind the scenes is an implementation detail. This lets us swap providers without touching feature code.</p><pre>class BaseAgent(ABC):<br>    @abstractmethod<br>    async def initialize(self) -&gt; None: ...<br>    @abstractmethod<br>    async def chat(self, message: str, **kwargs) -&gt; Dict[str, Any]: ...<br>    @abstractmethod<br>    async def stream_chat(self, message: str, **kwargs): ...<br>    @abstractmethod<br>    async def create_session(self, metadata: Optional[Dict[str, Any]] = None) -&gt; str: ...<br>    @abstractmethod<br>    async def delete_session(self, session_id: str) -&gt; bool: ...</pre><p>Some agents might internally use Azure AI Foundry threads and runs; others might pipe directly to Azure OpenAI. From the module’s perspective, they’re all just BaseAgent instances.</p><p>Effect: You can swap implementation details (e.g. migrate a workflow from “raw Azure OpenAI” to “AI Foundry agents”) with minimal impact on feature modules.</p><h4>3. A Single Source of Truth for Azure Clients</h4><p>All adapters are created through a central ClientFactory. It caches clients and manages a shared HTTP connection pool per Azure endpoint. This prevents every new feature from creating its own isolated connections, which silently kills throughput and saturates ports.</p><p>Pseudo‑code:</p><pre>from shared.clients.factory import ClientFactory<br>factory = ClientFactory()<br>llm_adapter = factory.create_adapter(<br>    adapter_type=&quot;azure_openai&quot;,<br>    config={<br>        &quot;endpoint&quot;: &quot;...&quot;,<br>        &quot;api_version&quot;: &quot;2024-08-01-preview&quot;,<br>        &quot;chat_model&quot;: &quot;gpt-4o-mini&quot;,<br>        &quot;auth&quot;: {&quot;type&quot;: &quot;api_key&quot;, &quot;api_key&quot;: &quot;...&quot;}<br>    }<br>)</pre><p>Under the hood:</p><ul><li>ClientFactory hashes key config fields to derive a cache key.</li><li>If an adapter with the same config already exists, it returns that instance.</li><li>When AzureOpenAIAdapter is initialized, it asks ClientFactory for a shared HTTP client for that endpoint, so multiple adapters share a single connection pool.</li></ul><p>Effect: High‑throughput services don’t accidentally create hundreds of isolated clients; everything flows through a predictable, reusable pool.</p><h4>4. A Universal Streaming Model</h4><p>We defined a single StreamingEventType enum (THINKING, CONTENT_CHUNK, ERROR, COMPLETED ,DONE ,THREAD_CREATEDetc.) and one WebSocket endpoint (/ws/{thread_id}) for the entire app. Every AI feature whether a simple chatbot or a complex agent converts its native stream into these standard events.</p><pre>{<br>  &quot;event_type&quot;: &quot;content_chunk&quot;,<br>  &quot;thread_id&quot;: &quot;123&quot;,<br>  &quot;data&quot;: { &quot;text&quot;: &quot;partial token...&quot; }<br>}</pre><p>Everything is then broadcasted to all WebSocket listeners for that thread_id.</p><p>Effect: Frontends only need to know about StreamingEventType and the thread ID; backend internals (OpenAI vs AI Foundry, RAG vs plain chat) become implementation details.</p><h3>How It All Fits Together: A Guided Tour</h3><p>Let’s connect the principles to the key building blocks you’d actually implement.</p><p>Step 1: Define Dependencies in Config. Each module’s agents.json defines its AI agents and links them to the adapters from module.json.</p><p>Step 2: The System Bootstraps Itself. On startup, the AgentFactory reads this config, asks the ClientFactory for the correct cached adapters, and instantiates ready-to-use BaseAgent objects.</p><p>Step 3: Features Just Talk to Agents. A feature module gets its agent and simply calls agent.stream_chat(message). It doesn&#39;t know about SDKs, connection pools, or secret management.</p><p>Step 4: Streaming “Just Works.” The agent uses the adapter to get a raw stream from Azure, transforms it into standard StreamingEventType events, and the shared WebSocketManager broadcasts it to the correct frontend thread.</p><h3>The Payoff: What This Architecture Enabled</h3><p>This shift transformed our development cycle:</p><ul><li>Speed: New AI features are now about business logic, not Azure boilerplate. What took days now takes hours.</li><li>Safety: Credential rotation is a one-line environment variable change. We can see every dependency at startup.</li><li>Consistency: Every feature has the same resilience (retries, timeouts) and the same smooth streaming UX.</li><li>Flexibility: We’ve swapped out underlying LLM providers for entire workflows with minimal impact, future-proofing our investment.</li></ul><p>We moved from fighting configuration fires to reliably shipping AI capabilities. This foundation is what allows us to scale to dozens of agents without collapsing under technical debt.</p><p>More posts are coming covering streaming, tools, real‑world case studies, and production hardening. Stay tuned.</p><p>Finally, a huge thank you to my team for designing and building this architecture <a href="https://www.linkedin.com/company/tryloop/posts/?feedView=all">TryLoop</a> . This shared layer has made it possible to ship multiple AI features quickly and reliably</p><p>#Azure #AI #ArtificialIntelligence #SoftwareArchitecture #TechBlog</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83d8a7c68908" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling a Million Concurrent Tasks? How .NET Orleans Makes It Feel Like One Machine]]></title>
            <link>https://medium.com/@Monem_Benjeddou/handling-a-million-concurrent-tasks-how-net-orleans-makes-it-feel-like-one-machine-8fa0acc5136f?source=rss-f0e9b44f6996------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fa0acc5136f</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[dotnetorleans]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Monem Benjeddou]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 16:47:59 GMT</pubDate>
            <atom:updated>2025-06-09T16:51:07.509Z</atom:updated>
            <content:encoded><![CDATA[<h3>Handling a Million Concurrent Tasks? How .NET Orleans Makes It Feel Like One Machine</h3><p>Picture this: you’re building a system to juggle millions of users or transactions, and it scales almost effortlessly — yet your code feels like it’s running on your laptop. That’s the magic of .NET Orleans and its take on the Actor Model. I’ve been down the distributed systems rabbit hole, and let me tell you, Orleans is a game-changer. In this post, we’ll unpack the Actor Model, look at real-world examples, and dig into the clustering tricks that make Orleans production-ready.</p><h3>The Actor Model: Taming Chaos with Simplicity</h3><p>Back in 1973, the Actor Model came to life, and honestly, it’s aged like fine wine. It’s a way to handle the madness of distributed systems without losing your mind. Here’s the gist:</p><ul><li><strong>Actors</strong> are like tiny, independent workers with their own state (data) and behavior (logic).</li><li>They talk to each other through async messages — no messy shared memory to worry about.</li><li>Each actor processes one message at a time, so you can kiss threading headaches goodbye.</li><li>They’re location-transparent, meaning you don’t need to know if they’re on your server or halfway across the globe.</li></ul><blockquote>Why’s this a big deal? Think of actors like cells in your body — trillions of them work solo but together power massive systems. WhatsApp (2 billion users!) and financial platforms lean on this model to keep things humming. It’s not just theory; it’s battle-tested.</blockquote><h3>What’s .NET Orleans, Anyway?</h3><p>Orleans is Microsoft’s open-source framework that takes the Actor Model and sprinkles some serious magic on it with “Virtual Actors.” Here’s what makes it special:</p><ul><li><strong>Automatic lifecycle management</strong>: Actors pop in and out of existence as needed — no manual babysitting.</li><li><strong>Logical addressing</strong>: You reference actors by simple IDs (like CartActor_User123), not some cryptic network address.</li><li><strong>Built-in persistence</strong>: Actors can save their state to Azure Table Storage, PostgreSQL, or Redis, so crashes don’t wipe them out.</li><li><strong>Failure-proof design</strong>: If something goes wrong, actors bounce back on another node like nothing happened.</li></ul><p>I’ve worked on systems where half my time was spent wrangling infrastructure. With Orleans, I could focus on the actual app logic — game-changer.</p><h3>Clustering: The Secret Sauce for Scaling</h3><p>Orleans runs on “silos” (think servers or nodes) that form a cluster. This is where the scalability kicks in:</p><ul><li><strong>Dynamic scaling</strong>: Got a traffic spike? Spin up more silos, and Orleans redistributes actors without breaking a sweat.</li><li><strong>Self-healing</strong>: If a silo crashes, actors just pop up elsewhere in the cluster.</li><li><strong>Zero-downtime upgrades</strong>: You can update your system while it’s still serving users. Try doing that with a traditional setup.</li></ul><h4>Clustering Models &amp; When to Use Them</h4><p>Orleans offers flexible clustering providers, so you can pick what fits your setup. For cloud deployments, I’m a big fan of Kubernetes clustering — it plays nice with Helm charts and makes silo discovery a breeze. If you’re on-prem, something like Consul might be your jam. Choose based on your infra, but Kubernetes is my go-to for anything cloud-native.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r-3VMDr6Tef8m2zXq3vExA.png" /><figcaption>Orleans usage</figcaption></figure><h3>Why Big Players Love Orleans</h3><p>Orleans powers some seriously impressive systems. Here’s a peek at where it shines:</p><ul><li><strong>Real-time apps</strong>: Think chat platforms or IoT dashboards juggling a million devices.</li><li><strong>Transactional workloads</strong>: Shopping carts, inventory systems — you name it.</li><li><strong>Event sourcing</strong>: Fraud detection or order processing pipelines that need to track every step.</li><li><strong>Big names</strong>: Microsoft uses Orleans for Halo’s multiplayer backend. Adobe Campaign cranks out 5 billion emails daily with it. Even Microsoft’s eShopOnContainers demo uses Orleans for baskets and orders.</li></ul><p>I once worked on a project where we needed sub-second responses for a real-time dashboard. Orleans made it feel like we were working with a single database, not a distributed mess.</p><h3>Why Orleans Matters in 2025</h3><p>Cloud-native apps are all about elasticity — handling spikes without crashing or costing a fortune. Traditional stateless microservices often choke on database calls, but Orleans keeps state in-memory with rock-solid reliability:</p><ul><li><strong>Speed</strong>: State access is 100x faster than database roundtrips.</li><li><strong>Low latency</strong>: Sub-millisecond responses for real-time needs.</li><li><strong>Scalability</strong>: Add more silos, and your system grows. No need to rewrite your code.</li></ul><h3>🔜 Coming Soon: Get Your Hands Dirty</h3><p>Want to try Orleans yourself? Tomorrow, I’m dropping a tutorial called <strong>“Building Your First Orleans App.”</strong> We’ll walk through:</p><ul><li>Setting up an ADO.NET cluster (it’s easier than it sounds).</li><li>Writing your first actors (with code you can copy-paste).</li><li>Saving state to a SQL database for persistence.</li></ul><h3>Wrapping Up</h3><p>.NET Orleans isn’t just a framework; it’s like having a superpower for distributed systems. It abstracts away the nasty bits — clustering, persistence, scaling — so you can focus on building something awesome. Whether you’re at a startup or modernizing a creaky enterprise system, Orleans is worth a look. In the cloud-native era, the future’s looking pretty actor-shaped.</p><p>Have you played with Orleans? Got any epic wins or war stories? Drop them in the comments — I’d love to hear!<br>Want more? Check out the <a href="https://github.com/dotnet/orleans">GitHub repo</a> or <a href="https://dotnet.github.io/orleans/">official docs</a>.</p><p><em>#DotNet #Orleans #ActorModel #DistributedSystems #CloudNative #Kubernetes #Microservices</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7b-_FqNWUavUCiVit1Zyiw.png" /><figcaption>Orleans Worls</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fa0acc5136f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Async/Await in .NET: Essential Tips, Performance Secrets, and Pro Patterns]]></title>
            <link>https://medium.com/@Monem_Benjeddou/mastering-async-await-in-net-essential-tips-performance-secrets-and-pro-patterns-88752c65ae0f?source=rss-f0e9b44f6996------2</link>
            <guid isPermaLink="false">https://medium.com/p/88752c65ae0f</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Monem Benjeddou]]></dc:creator>
            <pubDate>Thu, 13 Mar 2025 23:53:35 GMT</pubDate>
            <atom:updated>2025-03-21T15:42:45.168Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Async/Await in .NET: Essential Tips, Performance Secrets, and Pro Patterns</h3><p>Async/await transformed .NET development, but most developers only scratch the surface. Let’s dive deep into professional-grade patterns, performance hacks, and subtle traps — including ways to optimize your code that aren’t obvious from official docs.</p><h3>🔥 1. The Silent Thread Killer: Async Mismatch</h3><p><strong>You’re Probably Doing This Wrong:</strong></p><pre>public string LoadData() // ← Sync method pretending to be async<br>{<br>    return FetchDataAsync().Result; // 😱 Timebomb for deadlocks!<br>}</pre><p>I once debugged a production outage where this pattern caused ASP.NET to exhaust all thread pool threads. The app became completely unresponsive under load.</p><p><strong>Pro Fix:</strong></p><pre>public async Task&lt;string&gt; LoadDataAsync() // True async all the way<br>{<br>    return await FetchDataAsync(); // Let async breathe through the stack<br>}</pre><p><strong>Golden Rule:</strong> If you catch yourself typing .Result or .Wait(), hear alarm bells. Async code should propagate like a wave through your entire architecture.</p><h3>⚡ 2. ConfigureAwait: Your Secret Performance Weapon</h3><p><strong>Library Developer’s Best Friend:</strong></p><pre>public async Task&lt;Data&gt; ProcessAsync()<br>{<br>    var data = await FetchDataAsync().ConfigureAwait(false); // 🚀 Escape context capture<br>    return Transform(data); // Runs on thread pool, not UI/main context<br>}</pre><p><strong>Real-World Impact:</strong><br>While developing the <a href="https://github.com/bmdrm/BMDRM.LibSql.git">libsql driver for EF Core</a>, I discovered why Microsoft’s team religiously uses ConfigureAwait(false) in database operations. In their RelationalCommand implementation, you&#39;ll see:</p><pre>public virtual async Task&lt;RelationalDataReader&gt; ExecuteReaderAsync(<br>    RelationalCommandParameterObject parameterObject,<br>    CancellationToken cancellationToken = default)<br>{<br>    // ...<br>    await connection.OpenAsync(cancellationToken)<br>      .ConfigureAwait(false); // ← Critical for library code<br>    // ...<br>}</pre><p>Key targets:</p><ol><li><strong>ASP.NET Core</strong> (no SynchronizationContext needed)</li><li><strong>UI apps</strong> (WPF/WinForms context switching)</li><li><strong>Microservices</strong> (high-throughput pipelines)</li></ol><p><strong>Golden Exception:</strong> When working with context-bound objects like UI controls, <em>don’t</em> use ConfigureAwait(false) after the await. Your WPF button handler needs the dispatcher context to update UI elements!</p><h3>💣 3. Async Void: The App Crash Catalyst</h3><p><strong>Disaster Code:</strong></p><pre>public async void ButtonClick(object sender, EventArgs e)<br>{<br>    await SaveDataAsync(); // 💥 Unhandled exceptions crash the process!<br>}</pre><p><strong>Survival Strategy:</strong></p><pre>public async Task SafeClickAsync(object sender, EventArgs e)<br>{<br>    try {<br>        await SaveDataAsync();<br>    }<br>    catch (Exception ex) {<br>        Logger.Log(ex); // Now we can handle errors<br>    }<br>}<br><br>// Wire-up with fire-and-forget pattern<br>void ButtonClick(object sender, EventArgs e) =&gt; <br>    SafeClickAsync(sender, e).ConfigureAwait(false);</pre><p><strong>Nugget of Wisdom:</strong> In 3years of .NET, I’ve seen async void cause 3 major production incidents. Treat it like radioactive material — handle with extreme care.</p><h3>🚀 4. Parallel Async Mastery: Beyond the Basics</h3><p><strong>Smart Batching:</strong></p><pre>public async Task&lt;UserProfile&gt; LoadFullProfileAsync(int userId)<br>{<br>    // Launch all independent tasks first<br>    var userTask = _api.GetUserAsync(userId);<br>    var ordersTask = _db.Orders.GetByUserAsync(userId);<br>    var imagesTask = _blobStorage.GetAvatarsAsync(userId);<br><br>    // Await all together (no nested awaits!)<br>    await Task.WhenAll(userTask, ordersTask, imagesTask);<br><br>    // Process results (no async tax here)<br>    return new UserProfile(<br>        userTask.Result,<br>        ordersTask.Result,<br>        imagesTask.Result);<br>}</pre><p><strong>Pro Tip:</strong> Combine with ValueTask for hot paths to reduce heap allocations:</p><pre>public async ValueTask&lt;CacheItem&gt; GetCachedItemAsync(string key)<br>{<br>    if (_cache.TryGet(key, out var item))<br>        return item; // ← Synchronous path, no allocation!<br><br>    return await FetchFromNetworkAsync(key); // ← Async path<br>}</pre><h3>🕰️ 5. Cancellation Like a Ninja</h3><p><strong>Modern .NET Pattern (No More CancellationTokenSource Chaos):</strong></p><pre>public async Task ProcessDataAsync(<br>    CancellationToken ct = default,<br>    int bufferSize = 4096)<br>{<br>    using var buffer = MemoryPool&lt;byte&gt;.Shared.Rent(bufferSize);<br>    await using var stream = GetDataStream();<br><br>    while (await stream.ReadAsync(buffer.Memory, ct) &gt; 0)<br>    {<br>        ProcessChunk(buffer.Memory.Span);<br>        ct.ThrowIfCancellationRequested(); // Respect cancellation<br>    }<br>}</pre><p><strong>Critical Insight:</strong> Always flow cancellation tokens through async layers. I’ve fixed memory leaks where abandoned tasks kept running because cancellation wasn’t properly propagated.</p><h3>🌊 6. Async Streams: The Hidden Gem (C# 8+)</h3><p><strong>Database Streaming Done Right:</strong></p><pre>public async IAsyncEnumerable&lt;Order&gt; StreamLargeDatasetAsync(<br>    [EnumeratorCancellation] CancellationToken ct = default)<br>{<br>    await using var conn = new SqlConnection(_config);<br>    await conn.OpenAsync(ct);<br><br>    var cmd = new SqlCommand(&quot;SELECT * FROM Orders&quot;, conn);<br>    await using var reader = await cmd.ExecuteReaderAsync(ct);<br><br>    var buffer = ArrayPool&lt;Order&gt;.Shared.Rent(100); // ← Pooling for perf<br>    <br>    while (await reader.ReadAsync(ct))<br>    {<br>        yield return MapOrder(reader);<br>        <br>        if (++count % 100 == 0)<br>            ArrayPool&lt;Order&gt;.Shared.Return(buffer); // Recycle memory<br>    }<br>}</pre><p><strong>Next-Level Move:</strong> Pair with System.Threading.Channels for high-throughput producer/consumer scenarios:</p><pre>var channel = Channel.CreateBounded&lt;Data&gt;(1000); <br><br>// Producer<br>async Task ProduceAsync()<br>{<br>    await foreach (var item in StreamLargeDatasetAsync())<br>    {<br>        await channel.Writer.WriteAsync(item);<br>    }<br>    channel.Writer.Complete();<br>}<br><br>// Consumer<br>async Task ConsumeAsync()<br>{<br>    await foreach (var item in channel.Reader.ReadAllAsync())<br>    {<br>        Process(item);<br>    }<br>}</pre><h3>🧪 Performance-Critical Async Checklist</h3><ol><li><strong>Pool Everything:</strong> Use ArrayPool&lt;T&gt;, MemoryPool&lt;T&gt; for buffers</li><li><strong>ValueTask Over Task:</strong> When synchronous completion is common</li><li><strong>Avoid Closure Allocations:</strong> Use static lambdas where possible</li><li><strong>Timer Wisdom:</strong> Use PeriodicTimer (no callbacks!) in .NET 6+</li><li><strong>Async Composition:</strong> Prefer await Task.WhenAll() over sequential awaits</li></ol><pre>// Zero-allocation async timer (C# 9+)  <br>public static async Task RunTimerAsync()<br>{<br>    using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1));<br>    <br>    while (await timer.WaitForNextTickAsync())<br>    {<br>        await ProcessBatchAsync(); // No callback hell!<br>    }<br>}</pre><h3>🕵️♂️ Becoming Undetectable: Write Async Code That Feels Human</h3><ol><li><strong>KISS Principle:</strong> Favor await Task.Delay(100) over complex state machines</li><li><strong>Context Matters:</strong> In UI apps, sometimes you <em>want</em> the main thread context</li><li><strong>Fail Fast:</strong> Validate async parameters immediatel</li></ol><pre>public async Task&lt;Result&gt; ProcessAsync(Input input)<br>{<br>    if (input is null) throw new ArgumentNullException(nameof(input)); // ← Sync check<br>    return await _processor.ProcessInternalAsync(input);<br>}</pre><ol><li><strong>Log Like a Pro:</strong> Use ActivityId for correlating async flows</li><li><strong>Know Your Tools:</strong> Use VS’s Parallel Stacks window religiously</li></ol><h3>Final Wisdom from the Trenches</h3><ul><li><strong>Async != Magic:</strong> Each await has overhead—measure with Benchmark.NET</li><li><strong>CPU-bound?</strong> Task.Run() is your friend, but don&#39;t abuse it</li><li><strong>Task.Result:</strong> Only safe if you <strong>100% know</strong> the task is completed</li><li><strong>Cancellation:</strong> Implement it early — it’s harder to add later</li><li><strong>Testing:</strong> Use Task.CompletedTask, ValueTask mocks extensively</li></ul><p>Remember: The best async code is boring — predictable, maintainable, and uneventful in production. Master these patterns, and you’ll write async code that’s not just fast, but truly bulletproof. 🚀</p><p>#dotnet #asyncawait #efcore #softwareengineering #codingtips #aspnetcore #performanceoptimization #backenddevelopment #csharp #dotnetcore #techtips #programming #codearchitecture #microservices #devcommunity</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3OXdWt5H1J1KqVucJQ_tOg.png" /><figcaption>Optimize your code</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88752c65ae0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Added a Turso/libSQL Connector to SeaweedFS Filer]]></title>
            <link>https://medium.com/@Monem_Benjeddou/how-i-added-a-turso-libsql-connector-to-seaweedfs-filer-f670ff14e405?source=rss-f0e9b44f6996------2</link>
            <guid isPermaLink="false">https://medium.com/p/f670ff14e405</guid>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[databse]]></category>
            <category><![CDATA[libsql]]></category>
            <category><![CDATA[seaweedfs]]></category>
            <category><![CDATA[turso]]></category>
            <dc:creator><![CDATA[Monem Benjeddou]]></dc:creator>
            <pubDate>Mon, 03 Mar 2025 10:11:09 GMT</pubDate>
            <atom:updated>2025-03-03T10:11:09.238Z</atom:updated>
            <content:encoded><![CDATA[<p><em>If you’ve used my </em><a href="https://github.com/bmdrm/BMDRM.LibSql.git"><em>libSQL driver for Entity Framework Core</em></a><em> to bridge .NET apps with Turso’s edge-ready SQLite, you’ll love this next chapter: integrating Turso directly into </em><strong><em>SeaweedFS</em></strong><em>, a distributed file system!</em></p><p>When building tools for modern infrastructure, I’m obsessed with marrying simplicity with scale. After creating a libSQL connector for EF Core to simplify .NET database workflows, I wondered: <em>Could Turso’s lightweight SQLite engine also supercharge metadata storage for distributed file systems?</em> Turns out, yes!</p><p>In this tutorial, I’ll show you how I added a <strong>Turso/libSQL backend</strong> to SeaweedFS’s filer — the same way you’d plug EF Core into a .NET app — but for managing petabytes of file metadata across global edge nodes. Let’s dive in! 🚀</p><h3>Why Turso?</h3><ul><li><strong>SQLite compatibility</strong>: No need to learn a new query language.</li><li><strong>Edge-friendly</strong>: Perfect for globally distributed apps.</li><li><strong>Low latency</strong>: Faster metadata operations for SeaweedFS directories.</li></ul><h3>Step 1: Create the Turso Store Implementation</h3><p>First, I created turso_store.go to handle database initialization and queries. Here’s the key part:</p><pre>package turso<br><br>import (<br> &quot;database/sql&quot;<br> &quot;fmt&quot;<br> _ &quot;github.com/lib/pq&quot;<br> &quot;github.com/seaweedfs/seaweedfs/weed/filer&quot;<br> &quot;github.com/seaweedfs/seaweedfs/weed/filer/abstract_sql&quot;<br> &quot;github.com/seaweedfs/seaweedfs/weed/util&quot;<br> _ &quot;github.com/tursodatabase/libsql-client-go/libsql&quot;<br>)<br><br>func init() {<br> filer.Stores = append(filer.Stores, &amp;Store{})<br>}<br><br>type Store struct {<br> abstract_sql.AbstractSqlStore<br>}<br><br>func (store *Store) GetName() string {<br> return &quot;libsql&quot;<br>}<br><br>func (store *Store) Initialize(configuration util.Configuration, prefix string) (err error) {<br> createTable := `CREATE TABLE IF NOT EXISTS &quot;%s&quot; (dirhash BIGINT, name VARCHAR(255), meta BLOB, PRIMARY KEY (dirhash, name)) ...;`<br> upsertQuery := `INSERT INTO &quot;%s&quot;(dirhash,name,meta) VALUES(?,?,?) ON CONFLICT(dirhash,name) DO UPDATE SET meta=excluded.meta ...;`<br> tursoURL := configuration.GetString(prefix + &quot;dbFile&quot;)<br> return store.initialize(tursoURL, createTable, upsertQuery)<br>}<br><br>func (store *Store) initialize(tursoURL, createTable, upsertQuery string) (err error) {<br><br> store.SupportBucketTable = true<br> store.SqlGenerator = &amp;SqlGenTurso{<br>  CreateTableSqlTemplate: &quot;&quot;,<br>  DropTableSqlTemplate:   `drop table &quot;%s&quot;`,<br>  UpsertQueryTemplate:    upsertQuery,<br> }<br> var dbErr error<br><br> store.DB, err = sql.Open(&quot;libsql&quot;, tursoURL)<br> switch {<br> case dbErr != nil:<br>  if store.DB != nil {<br>   err := store.DB.Close()<br>   if err != nil {<br>    return err<br>   }<br>   store.DB = nil<br>  }<br>  return fmt.Errorf(&quot;can not connect to %s error:%v&quot;, tursoURL, dbErr)<br> }<br><br> if err = store.DB.Ping(); err != nil {<br>  return fmt.Errorf(&quot;connect to %s error:%v&quot;, tursoURL, err)<br> }<br><br> store.DB.SetMaxOpenConns(1)<br><br> return nil<br>}</pre><h3>Step 2: Implement SQL Query Templates</h3><p>Next, I added turso_sql_gen.go to define Turso-specific SQL queries. SeaweedFS’s abstract_sql layer does most of the heavy lifting here:</p><pre>// weed/filer/turso/turso_sql_gen.go<br>package turso<br><br>import &quot;github.com/seaweedfs/seaweedfs/weed/filer/abstract_sql&quot;<br><br>type SqlGenTurso struct {<br>  UpsertQueryTemplate string<br>}<br><br>// Example: Query to list files in a directory<br>func (gen *SqlGenTurso) GetSqlListInclusive(table string) string {<br>  return fmt.Sprintf(`SELECT name, meta FROM &quot;%s&quot; <br>    WHERE dirhash=? AND name&gt;=? AND directory=? <br>    AND name LIKE ? ORDER BY name ASC LIMIT ?`, table)<br>}<br><br>// Other required methods (abbreviated for clarity)<br>func (gen *SqlGenTurso) GetSqlDelete(table string) string { /* ... */ }<br>func (gen *SqlGenTurso) GetSqlFind(table string) string   { /* ... */ }</pre><h3>Step 3: Update Filer Configuration</h3><p>To enable Turso, I updated the SeaweedFS filer configuration (filer.toml):</p><pre># Example filer.toml<br>[leveldb2]<br>enabled = false # Disable default backend<br><br>[libsql]<br>enabled = true<br>dbFile = &quot;libsql://your-database.turso.io?authToken=your-token&quot;</pre><p><strong>Turso URL Notes</strong>:</p><ul><li>Get your URL and token from the Turso dashboard.</li><li>Use libsql:// protocol for TLS connections.</li></ul><h3>Step 4: Test the Integration</h3><p>After rebuilding SeaweedFS, I ran the filer with:</p><pre>weed filer -master=localhost:9333 -filer.turso.config=filer.toml</pre><p><strong>Verification</strong>:</p><ol><li>Created a test file: echo &quot;Hello Turso&quot; &gt; test.txt</li><li>Checked Turso’s dashboard — metadata appeared instantly!</li></ol><h3>Key Takeaways</h3><ol><li><strong>Connection Limits</strong>: Turso’s HTTP API requires SetMaxOpenConns(1) to avoid timeouts.</li><li><strong>SQLite Syntax</strong>: Use ON CONFLICT for upserts, and WITHOUT ROWID for faster lookups.</li><li><strong>Edge Ready</strong>: Deploy filers globally, and let Turso handle sync!</li></ol><h3>Why This Works Well</h3><ul><li><strong>Performance</strong>: SQLite’s embedded engine + Turso’s edge network = fast metadata ops.</li><li><strong>Simplicity</strong>: No external database clusters to manage.</li><li><strong>Cost</strong>: Turso’s free tier is generous for small/medium projects.</li></ul><h3>Try It Yourself!</h3><ol><li>Fork the <a href="https://github.com/seaweedfs/seaweedfs">SeaweedFS repo</a>.</li><li>Add the Turso store code .</li><li>Configure your filer and deploy!</li></ol><p>Hit a snag? DM me on LinkedIn [@<a href="https://www.linkedin.com/in/benjeddou-monem-63ab50175/overlay/about-this-profile/">Benjeddou Monem</a> (Dev@BMDRM)] — I’m happy to help! 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vQQ3ECVZCRAH3jFeNOcInw.jpeg" /></figure><p>#SeaweedFS #Turso #libSQL #SQLite #DistributedSystems #CloudNative #EdgeComputing #Database #OpenSource #DevCommunity</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f670ff14e405" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boost Your File Storage with SeaweedFS & PostgreSQL: A Step-by-Step Setup]]></title>
            <link>https://medium.com/@Monem_Benjeddou/boost-your-file-storage-with-seaweedfs-postgresql-a-step-by-step-setup-23c890a50327?source=rss-f0e9b44f6996------2</link>
            <guid isPermaLink="false">https://medium.com/p/23c890a50327</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[seaweedfs]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Monem Benjeddou]]></dc:creator>
            <pubDate>Sat, 22 Feb 2025 18:39:45 GMT</pubDate>
            <atom:updated>2025-02-22T18:39:45.823Z</atom:updated>
            <content:encoded><![CDATA[<p>SeaweedFS is a high-performance distributed storage system designed for simplicity and efficiency. While it excels at managing large volumes of files, its real power shines when paired with a robust metadata store like PostgreSQL. In this guide, we’ll walk through configuring SeaweedFS to use PostgreSQL for tracking file metadata, complete with code examples and practical explanations.</p><h3>Why Use PostgreSQL with SeaweedFS?</h3><p>By default, SeaweedFS uses LevelDB for storing metadata in its filer component. While LevelDB works for small setups, PostgreSQL offers significant advantages:</p><ol><li><strong>Scalability</strong>: Handle high-concurrency workloads.</li><li><strong>Durability</strong>: ACID compliance ensures data integrity.</li><li><strong>Query Flexibility</strong>: SQL enables complex metadata queries.</li><li><strong>Easier Maintenance</strong>: PostgreSQL’s tooling simplifies backups and monitoring.</li></ol><p>The key to this integration is the filemeta table, which replaces LevelDB’s key-value storage with a relational structure. Let’s break down why this table matters.</p><h3>The Heart of the System: The filemeta Table</h3><p>The filemeta table stores critical metadata about files and directories. Here’s the schema we’ll use (defined in check_create_filemeta.sh):</p><pre>CREATE TABLE IF NOT EXISTS filemeta (<br>  dirhash     BIGINT,<br>  name        VARCHAR(65535),<br>  directory   VARCHAR(65535),<br>  meta        bytea,<br>  PRIMARY KEY (dirhash, name)<br>);</pre><ul><li><strong>dirhash</strong>: A hash of the directory path for fast lookups.</li><li><strong>name</strong>: The filename or directory name.</li><li><strong>directory</strong>: Full directory path (e.g., /documents/reports).</li><li><strong>meta</strong>: Serialized file metadata (permissions, timestamps, etc.).</li></ul><p>The primary key (dirhash, name) ensures efficient lookups while avoiding row locks during concurrent writes.</p><h3>Setting Up the Environment</h3><h4>1. Docker Network and Volumes</h4><p>We start by defining a Docker network and persistent volumes in docker-compose.yml:</p><pre>networks:<br>  seaweed:<br>    driver: bridge<br><br>volumes:<br>  postgres_data:  # PostgreSQL data<br>  volume_data:    # SeaweedFS volume 1<br>  volume_data2:   # SeaweedFS volume 2</pre><p>This isolates our services while allowing communication between them.</p><h4>2. SeaweedFS Master and Volumes</h4><p>The master service coordinates the cluster, while volume/volume2 store actual file data:</p><pre>services:<br>  master:<br>    image: chrislusf/seaweedfs<br>    command: &quot;master -ip=master -defaultReplication=001&quot;<br>    ports: [&quot;9333:9333&quot;, &quot;19333:19333&quot;]<br>    networks: [&quot;seaweed&quot;]<br><br>  volume:<br>    command: &quot;volume -dir=/data -mserver=master:9333 -port=8080&quot;<br>    volumes: [&quot;volume_data:/data&quot;]<br>    depends_on: [&quot;master&quot;]<br><br>  volume2:<br>    command: &quot;volume -dir=/data2 -mserver=master:9333 -port=8081&quot;<br>    volumes: [&quot;volume_data2:/data2&quot;]</pre><ul><li>defaultReplication=001 ensures each file is replicated across two volumes.</li><li>Separate volume_data and volume_data2 volumes provide fault tolerance.</li></ul><h4>3. PostgreSQL Configuration</h4><p>A dedicated PostgreSQL instance stores our metadata:</p><pre>postgres:<br>  image: postgres:latest<br>  environment:<br>    POSTGRES_USER: seaweed<br>    POSTGRES_PASSWORD: seaweed<br>    POSTGRES_DB: seaweed<br>    POSTGRES_PORT: 5434<br>  healthcheck:<br>    test: [&quot;CMD-SHELL&quot;, &quot;pg_isready -U seaweed -h postgres -p 5434&quot;]<br>    interval: 5s<br>    timeout: 5s<br>    retries: 5<br>  volumes: [&quot;postgres_data:/var/lib/postgresql/data&quot;]</pre><ul><li>The healthcheck ensures the filer starts only after PostgreSQL is ready.</li><li>Persistent postgres_data volume safeguards against data loss.</li></ul><h4>4. Filer Service with PostgreSQL Integration</h4><p>The filer service acts as the gateway to SeaweedFS, using our PostgreSQL metadata:</p><pre>filer:<br>  image: chrislusf/seaweedfs<br>  depends_on:<br>    postgres:<br>      condition: service_healthy<br>  volumes:<br>    - &quot;./check_create_filemeta.sh:/scripts/check_create_filemeta.sh&quot;<br>    - &quot;./filer.toml:/etc/seaweedfs/filer.toml&quot;<br>  entrypoint: [&quot;/bin/sh&quot;, &quot;-c&quot;]<br>  command:<br>    - &quot;apk add --no-cache postgresql-client &amp;&amp; /scripts/check_create_filemeta.sh &amp;&amp; weed filer -master=master:9333&quot;</pre><ul><li>Installs postgresql-client to run the check_create_filemeta.sh script.</li><li>Executes the script before starting to ensure the filemeta table exists.</li></ul><h3>Key Configuration Files</h3><h4>check_create_filemeta.sh</h4><p>This script initializes the PostgreSQL table:</p><pre>#!/bin/sh<br>set -e<br>PGPORT=5434<br>PGPASSWORD=&quot;seaweed&quot; psql -h postgres -p &quot;$PGPORT&quot; -U seaweed -d seaweed -c &quot;<br>    CREATE TABLE IF NOT EXISTS filemeta (...);<br>&quot;<br>echo &quot;Table &#39;filemeta&#39; created or already exists.&quot;</pre><ul><li>set -e stops execution on errors (critical for initialization).</li><li>Explicitly sets the PostgreSQL port and credentials.</li></ul><h4>filer.toml</h4><p>Configures the filer to use PostgreSQL instead of LevelDB:</p><pre>[leveldb2]<br>enabled = false<br>[postgres]<br>enabled = true<br>createTable = true<br>username = &quot;seaweed&quot;<br>password = &quot;seaweed&quot;<br>database = &quot;seaweed&quot;<br>hostname = &quot;postgres&quot;<br>port = 5434<br>sslmode = &quot;disable&quot;</pre><ul><li>Disables LevelDB (enabled = false).</li><li>Specifies connection details for PostgreSQL.</li><li>createTable = true would auto-create the table, but we handle it via script for more control.</li></ul><h3>Starting the System</h3><ol><li>Run docker-compose up -d.</li><li>The filer waits for PostgreSQL to be healthy (via service_healthy condition).</li><li>The check_create_filemeta.sh script creates the table if missing.</li><li>The filer starts, connected to the master and PostgreSQL.</li></ol><h3>Why This Setup Works</h3><ol><li><strong>Fault Tolerance</strong>: Multiple volumes and PostgreSQL ensure data redundancy.</li><li><strong>Performance</strong>: PostgreSQL connection pooling handles concurrent filer requests.</li><li><strong>Simplicity</strong>: Docker Compose encapsulates the entire setup.</li></ol><p>By offloading metadata to PostgreSQL, you gain the ability to run complex queries (e.g., “Find all PDFs modified last week”) directly on the database, which isn’t possible with LevelDB. Plus, you’re leveraging a battle-tested RDBMS for critical metadata operations.</p><h3>Final Thoughts</h3><p>This configuration balances scalability and practicality. For production, consider tuning PostgreSQL (indexes, connection limits) and adding monitoring. You’ve now got a SeaweedFS cluster that’s ready to handle everything from personal projects to enterprise workloads — with metadata managed by a proven SQL database.</p><p>#SeaweedFS #PostgreSQL #DistributedStorage #DevOps #CloudStorage #DataEngineering #Docker #MetadataManagement #TechTutorial</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iU_rUvR-HjFdOLmc1qKHzQ.jpeg" /><figcaption>Futuristic Storage Symphony</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23c890a50327" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Saved 500+ Hours (and Our Sanity) Fixing LibSQL for .NET”]]></title>
            <link>https://medium.com/@Monem_Benjeddou/how-we-saved-500-hours-and-our-sanity-fixing-libsql-for-net-bb316efdac74?source=rss-f0e9b44f6996------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb316efdac74</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[turso]]></category>
            <category><![CDATA[ef-core]]></category>
            <category><![CDATA[libsql]]></category>
            <dc:creator><![CDATA[Monem Benjeddou]]></dc:creator>
            <pubDate>Thu, 30 Jan 2025 23:29:02 GMT</pubDate>
            <atom:updated>2025-01-30T23:40:35.168Z</atom:updated>
            <content:encoded><![CDATA[<h3>EF Core’s Missing LibSQL Driver? We Built It (And It Scales)</h3><p>We Almost Gave Up on LibSQL Until We Built This: The EF Core Driver That Should’ve Existed</p><p>As .Net devs, we spent nights debugging EF Core providers. But nothing prepared us for LibSQL.</p><p>We <em>loved</em> LibSQL’s vision — SQLite compatibility with distributed superpowers. But when we tried to adopt it last year, reality hit:</p><ul><li><strong>No Production-Ready EF Core Driver</strong>: Existing community hacks broke migrations, ignored transactions, or leaked connections.</li><li><strong>Endless Workarounds</strong>: We wasted 3 weeks retrofitting Microsoft.Data.Sqlite to handle LibSQL’s HTTP API. Time we’d promised to spend on features.</li><li><strong>Scaling Nightmares</strong>: Scaling? Total disaster at 10K RPS. Distributed locks in EF Core? We’d rather not relive it.</li></ul><p><strong>The Breaking Point</strong></p><p>At some point, we had to face it — our setup wasn’t sustainable. Every sprint, we were firefighting issues instead of shipping features. The final straw? A failed batch process that forced us into yet another long debugging session. That’s when we made the call: <em>Build it right, or abandon LibSQL.</em></p><p><strong>What We Cooked Up<br></strong>Meet EFCore.LibSQL.Core — the driver that finally makes LibSQL behave for .NET teams (well tested):</p><ol><li><strong>Connection Pooling That Doesn’t Suck</strong><br>(No more RAM-chugging zombie connections. We tested this by literally trying to break it.)</li><li><strong>Migrations That Don’t Lie</strong><br>Found 17 edge cases in LibSQL’s schema handling. Now dotnet ef migrations add just works - even with those weird collations your legacy system requires.</li><li><strong>Bulk Operations That Scale (Seriously)</strong><br>Hit very hight numbers in our stress tests using LibSQL’s pipeline mode. Your move, MongoDB.</li></ol><p><strong>The Moment We Knew We’d Won:<br></strong>Before<strong>:</strong></p><pre>using (var tx = await _client.BeginTransactionAsync())  <br>{  <br>    try  <br>    {  <br>        await _client.ExecuteAsync(&quot;INSERT...&quot;);  <br>        // 😱 Manual change tracking  <br>        await tx.CommitAsync();  <br>    }  <br>    catch  <br>    {  <br>        await tx.RollbackAsync();  <br>        throw;  <br>    }  <br>}  </pre><p>After :</p><pre>await _dbContext.Database.BeginTransactionAsync();  <br>_dbContext.Orders.AddRange(batch);  <br>await _dbContext.SaveChangesAsync(); // ACID, retries, etc.  <br>await _dbContext.Database.CommitTransactionAsync(); </pre><p><strong>Why This Will Save Your Team</strong></p><ul><li><strong>Reclaim 1 Day/Week</strong> from debugging driver nonsense</li><li><strong>Deploy to edge + cloud</strong> with <em>identical</em> code</li><li><strong>Sleep through migrations</strong> (yes, even on Fridays)</li></ul><p><strong>Get Started in 5 Minutes</strong></p><p>Step 1: Add the NuGet package:</p><pre>~$ dotnet add package BMDRM.LibSql.Core --version 8.0.32</pre><p>Step 2: Configure the DbContext</p><pre>services.AddDbContext&lt;AppDbContext&gt;(options =&gt;  <br>    options.UseLibSql(Configuration.GetConnectionString(&quot;LibSQL&quot;)));  </pre><p>or</p><pre>protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  <br>{  <br>    if (!optionsBuilder.IsConfigured)  <br>    {  <br>        optionsBuilder.UseLibSql(&quot;https://example.turso.io...;jwt=xyz&quot;);  <br>    }  <br>}</pre><p>Step 3: Migrate and Scale</p><pre>~$ dotnet ef database update</pre><p>This isn’t some academic project. We built EFCore.LibSQL.Core because we needed to ship features, not fight the database layer.</p><p><strong>Join the Rebellion : </strong><a href="https://github.com/bmdrm/BMDRM.LibSql.git">GitHub Repo</a></p><p>We appreciate bug reports, feature requests, and, of course, code contributions!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQsdlORKWRjgQ7FkN1KiUA.jpeg" /><figcaption>Before and after</figcaption></figure><p>Software engineer at <a href="https://bmdrm.com/">BMDRM</a></p><p>#EFCore #LibSQL #DotNET #DeveloperProductivity #Turso #Database</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb316efdac74" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>