<?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 Ferhat Talha BULANIK on Medium]]></title>
        <description><![CDATA[Stories by Ferhat Talha BULANIK on Medium]]></description>
        <link>https://medium.com/@ferhatblnk?source=rss-d2887a0d5055------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LCIb6BslNW_TLQe24ask4w.jpeg</url>
            <title>Stories by Ferhat Talha BULANIK on Medium</title>
            <link>https://medium.com/@ferhatblnk?source=rss-d2887a0d5055------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 22:34:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ferhatblnk/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[Your Company Doesn’t Need Another AI Assistant. It Needs a Connector.]]></title>
            <link>https://medium.com/@ferhatblnk/your-company-doesnt-need-another-ai-assistant-it-needs-a-connector-d3f7c6c85415?source=rss-d2887a0d5055------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3f7c6c85415</guid>
            <category><![CDATA[api-security]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Ferhat Talha BULANIK]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 06:29:30 GMT</pubDate>
            <atom:updated>2026-10-23T06:29:30.857Z</atom:updated>
            <content:encoded><![CDATA[<p>Most teams are wiring Claude to their systems with duct tape, or not at all. Here is how to build an MCP connector that survives production: token custody, SOLID server design, business rule sets, and the disconnect button nobody tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZMUDZ_GYLrrQcAsgD5lbag.jpeg" /></figure><p>A few months ago I sat in a meeting where a company proudly demoed its new AI rollout. Everyone had a Claude seat. People were drafting emails faster, summarizing long documents, cleaning up meeting notes. All good things.</p><p>Then someone from operations asked a simple question: “Can it tell me which orders from last week are stuck in the warehouse and why?”</p><p>It couldn’t. Not because the model wasn’t smart enough, but because it had no way in. The orders lived in an ERP, the warehouse status lived in a separate system with its own API, and the “why” lived in a ticketing tool. The model was a brilliant new hire who had been given a laptop and no logins.</p><p>That gap is where most companies are right now. They buy the seats, they run the workshops, and they skip the part that actually compounds: giving the model safe, well-defined access to the systems where the business really happens. On Claude, that part is called a <strong>connector</strong>, and underneath every connector is an <strong>MCP server</strong>.</p><p>This article is about building that layer properly. Not a weekend demo that wraps three endpoints, but something your security team will sign off on and your platform team will still be happy to own a year from now.</p><p>I will keep the API side deliberately thin. We will talk about endpoints and triggers, because a connector has to call something, but the focus is the MCP server and the connector contract around it: architecture, protocol, business rules, and the lifecycle of credentials from connect to disconnect.</p><h3>What a connector actually is</h3><p>Strip away the product naming and a connector is three things:</p><ol><li><strong>A remote MCP server</strong> that exposes your capabilities as tools (and optionally resources and prompts).</li><li><strong>An authorization relationship</strong> between a user, Claude, your MCP server and, usually, the upstream system the server talks to.</li><li><strong>A business contract</strong>: the set of rules that decides what those tools are allowed to do, for whom, and under what conditions.</li></ol><p>Claude plays the MCP client. When a user adds your connector, Claude discovers your server’s tools, the user goes through an OAuth consent screen, and from then on the model can call your tools inside a conversation.</p><p>Most teams think about item 1, some think about item 2, and almost nobody designs item 3 on purpose. Item 3 is where the value is.</p><h3>Why this matters more than it looks</h3><p>An API answers “what can this system do?”. A good connector answers “what should an assistant be able to do in this business, on behalf of this person, right now?”.</p><p>Those are very different questions. The first gives you 140 endpoints. The second gives you maybe twelve tools, each one shaped around a real task: <em>find stuck orders</em>, <em>explain a shipment delay</em>, <em>draft a refund for approval</em>. Each of those tools carries the knowledge your senior people keep in their heads: which statuses count as “stuck”, which refunds need a second approver, which customers are under a legal hold.</p><p>When you encode that once in an MCP server, every person who talks to Claude gets it for free. That is the leverage people miss. You are not building an integration; you are publishing your operating procedures in a form a model can execute safely.</p><h3>The architecture: boring layers, sharp boundaries</h3><p>Here is the shape I keep coming back to. Nothing exotic, but every boundary is there for a reason.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HpZE8L_dPING0E39fgPI2Q.jpeg" /></figure><p>From the outside in:</p><ul><li><strong>Transport adapter.</strong> Streamable HTTP for a remote connector. This layer knows about HTTP, headers and streaming responses. It knows nothing about your business.</li><li><strong>Protocol layer.</strong> JSON-RPC parsing, protocol version negotiation, capability advertisement, tools/list, tools/call. Use the official SDK here instead of rolling your own.</li><li><strong>Identity and auth guard.</strong> Validates the access token Claude presents, checks the audience, resolves the user and tenant. No tool code runs before this succeeds.</li><li><strong>Tool registry.</strong> Each tool is a small module with a name, a description, input and output schemas, annotations and a reference to its rule set.</li><li><strong>Policy engine.</strong> Evaluates the business rule set for the tool against the caller, the input and the current state.</li><li><strong>Application services.</strong> The actual use cases: “find stuck orders”, “prepare refund draft”.</li><li><strong>Integration adapters.</strong> One adapter per upstream system. This is the only layer that knows about endpoints, upstream credentials and retry semantics.</li><li><strong>Credential broker.</strong> Fetches, refreshes and caches upstream tokens from a secret manager. Adapters ask the broker for a credential; they never read secrets directly.</li></ul><p>On the side, two cross-cutting pieces: an <strong>audit log</strong> that records every tool call with its decision, and <strong>telemetry</strong> that ties a model’s tool call to the upstream requests it caused.</p><h3>Where SOLID earns its keep</h3><p>SOLID gets thrown around a lot, so let me be concrete about what each principle buys you in an MCP server.</p><p><strong>Single responsibility.</strong> A tool definition describes; it does not execute. A service executes; it does not know about JSON-RPC. An adapter talks to one upstream system; it does not decide whether the call is allowed. When a rule changes, you touch the rule set. When an upstream API changes, you touch one adapter. When the MCP spec changes (and it does), you touch the protocol layer.</p><p><strong>Open/closed.</strong> Adding a tool should mean adding a file and registering it, not editing a switch statement in the request handler.</p><pre>export interface ToolModule&lt;I, O&gt; {<br>  name: string;<br>  description: string;<br>  inputSchema: JSONSchema;<br>  outputSchema: JSONSchema;<br>  annotations: ToolAnnotations;<br>  ruleSet: RuleSetId;<br>  execute(input: I, ctx: CallContext): Promise&lt;O&gt;;<br>}</pre><pre>registry.register(findStuckOrders);<br>registry.register(explainShipmentDelay);<br>registry.register(prepareRefundDraft);</pre><p><strong>Liskov substitution.</strong> Every adapter for “orders” should honor the same contract, whether it is backed by your production ERP, a sandbox or an in-memory fake for tests. If your test double behaves differently from the real adapter on errors or pagination, your tests are lying to you.</p><p><strong>Interface segregation.</strong> Do not hand a service a giant ErpClient with 80 methods. Give it OrderReader or RefundWriter. Small interfaces make it obvious, at code review, which tools can write and which can only read. That matters a lot once a model is choosing which tool to call.</p><p><strong>Dependency inversion.</strong> Services depend on interfaces such as OrderReader and CredentialProvider, never on concrete HTTP clients or a specific vault SDK. This is what lets you swap AWS Secrets Manager for HashiCorp Vault, or move from one ERP to another, without rewriting a single tool.</p><pre>class FindStuckOrders implements ToolModule&lt;FindStuckInput, StuckOrders&gt; {<br>  constructor(<br>    private readonly orders: OrderReader,<br>    private readonly warehouse: WarehouseStatusReader,<br>    private readonly clock: Clock,<br>  ) {}<br>  // ...<br>}</pre><p>None of this is novel. The point is that an MCP server is a long-lived integration surface sitting between a non-deterministic caller (the model) and your systems of record. The cost of a muddled design shows up faster here than in an ordinary internal service.</p><h3>Protocol and transport: design for the spec you will have next year</h3><p>MCP is a young protocol and it moves. The <strong>2026–07–28</strong> revision is a good example of why the protocol layer must be isolated. That revision removed protocol-level sessions and the Mcp-Session-Id header from Streamable HTTP, dropped the initialize handshake in favor of carrying the protocol version and client capabilities on every request, and added a server/discover method for capability and version discovery. Server-to-client requests such as elicitation were replaced by a multi round-trip pattern, where the server returns an &quot;input required&quot; result and the client retries with the answers.</p><p>If your business logic was tangled with session state, that revision was painful. If it lived behind a clean protocol layer, it was an SDK upgrade and a few tests.</p><p>A few principles that held up through every revision so far:</p><p><strong>Pick Streamable HTTP for connectors.</strong> stdio is for local servers running on a developer’s machine. A connector is remote, multi-tenant and authenticated, so it lives behind HTTPS.</p><p><strong>Be stateless by default.</strong> Every request should carry everything needed to process it: the token, the tenant, the arguments. If a workflow needs state across calls (a multi-step export, a draft that gets approved later), mint an explicit handle and pass it as a normal tool argument. Store the state in your database, keyed by that handle and scoped to the user. This scales horizontally and survives deploys, and it happens to be exactly where the spec has landed.</p><p><strong>Negotiate versions explicitly.</strong> Clients do not upgrade on the same day. Support the current revision and the previous one, reject what you do not support with a clear error, and keep a version matrix in your test suite.</p><p><strong>Make discovery deterministic and cheap.</strong> Return tools/list in a stable order and keep descriptions stable between deploys. Clients can cache them, and models behave more predictably when the tool menu does not shuffle.</p><p><strong>Propagate trace context.</strong> The spec documents OpenTelemetry conventions for traceparent in request metadata. Use them. When someone asks &quot;why did the assistant refund this customer?&quot;, you want one trace from the tool call down to the upstream request.</p><h3>The API side: endpoints and triggers, nothing more</h3><p>I promised to keep this thin. Your MCP server needs to know three things about each upstream system:</p><p>ConcernWhat to define<strong>Endpoints</strong>The handful of upstream operations each adapter uses. A tool rarely maps one-to-one to an endpoint.<strong>Triggers</strong>What causes a call: a user’s tool call (synchronous), an upstream webhook (cache invalidation, revocation), or a scheduled job (token refresh, sync).<strong>Credentials</strong>Which credential the adapter needs, and which scopes. Resolved through the credential broker, never inline.</p><p>Two triggers people forget: the <strong>webhook that tells you a user revoked access upstream</strong>, and the <strong>scheduled job that cleans up abandoned connections</strong>. Both matter in the disconnect section below.</p><p>Everything else about the API, such as pagination, rate limits and payload formats, belongs inside the adapter and should not leak into tool design.</p><h3>Tools as business capabilities, governed by rule sets</h3><p>This is the section I would print and hand to anyone starting a connector project.</p><h3>Design tools around tasks, not endpoints</h3><p>A tool called get_orders with fourteen optional filters forces the model to rediscover your business logic on every call, and it will get it subtly wrong. A tool called find_stuck_orders with two arguments (a date range and an optional warehouse) encodes the definition of &quot;stuck&quot; once, correctly.</p><p>Good tool descriptions read like instructions to a careful colleague: what the tool is for, when not to use it, what the output means. Use output schemas so results are structured, and keep payloads small. A model does not need 200 fields per order. It needs the ten that answer the question.</p><h3>Every tool gets a rule set</h3><p>A rule set is the business contract for a single tool, kept outside the tool’s code so it can be reviewed by people who do not read TypeScript. Mine usually look something like this:</p><pre>tool: prepare_refund_draft<br>version: 3<br>owner: payments-team</pre><pre>access:<br>  required_scopes: [refunds:draft]<br>  roles_allowed: [support_agent, support_lead]<br>  tenants: all</pre><pre>annotations:<br>  readOnlyHint: false<br>  destructiveHint: false<br>  idempotentHint: true<br>  openWorldHint: false</pre><pre>preconditions:<br>  - order.status in [delivered, returned]<br>  - order.age_days &lt;= 60<br>  - customer.legal_hold == false</pre><pre>limits:<br>  max_amount: 500.00<br>  currency_must_match_order: true<br>  per_user_per_day: 25</pre><pre>approval:<br>  above_amount: 150.00<br>  mode: draft_only        # the tool never executes the refund itself</pre><pre>output:<br>  redact: [customer.email, payment.card_last4]<br>  max_items: 20</pre><pre>audit:<br>  level: full<br>  retain_days: 400</pre><p>A few things to notice.</p><p><strong>Scopes and roles are separate.</strong> The OAuth scope says what the token can do. The role says what this person is allowed to do in your business. You need both.</p><p><strong>Annotations are hints, not security.</strong> MCP tool annotations like readOnlyHint and destructiveHint help the client decide when to ask the user for confirmation. They are useful, and you should set them honestly, but your server enforces the real rules. Never rely on the client to protect your data.</p><p><strong>Preconditions use domain language.</strong> order.age_days &lt;= 60 is something a payments lead can read and approve. That review loop is the whole point.</p><p><strong>Write tools default to drafts.</strong> For anything with money, customers or legal exposure, the safest pattern is a tool that prepares the action and returns a handle, and a separate, explicitly confirmed step (in Claude or in your own UI) that executes it. Combined with stateless handles, this gives you a clean two-phase commit for model-initiated actions.</p><p><strong>Rule sets are versioned.</strong> Keep them in the repository, review them like code, and log the rule set version with every audit entry. Six months later, “why was this allowed?” has an exact answer.</p><h3>The call pipeline</h3><p>Put together, every tool call runs through the same pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MVTcGWY6sbVYK0jIJLV47Q.jpeg" /></figure><ol><li>Validate the inbound token: signature, expiry, audience, issuer.</li><li>Resolve the user, tenant and role.</li><li>Validate input against the tool’s schema.</li><li>Evaluate the rule set: scopes, roles, preconditions, limits.</li><li>Ask the credential broker for the upstream credential.</li><li>Execute the service through its adapters.</li><li>Shape the output: redact, trim, attach handles.</li><li>Write the audit record with the decision and rule set version.</li></ol><p>When a rule fails, return a clear, model-readable error (“Refunds above 150.00 require approval; a draft was not created.”) rather than a stack trace. The model will relay it to the user, and a good error message often saves a support ticket.</p><h3>Token custody: the part that keeps security teams up at night</h3><p>There are two kinds of tokens in a connector, and confusing them is the most common serious mistake I see.</p><p><strong>Inbound tokens</strong> are what Claude sends to your MCP server. Your server is an OAuth resource server. It must validate that the token was issued for <em>it</em>. The spec requires clients to send a resource parameter (RFC 8707) identifying your server, and requires servers to validate the audience. If your server accepts any valid token from your identity provider, you have a confused-deputy problem waiting to happen.</p><p><strong>Upstream tokens</strong> are what your server uses to call your ERP, CRM or ticketing system on the user’s behalf. These are yours to protect.</p><p>The rule that ties them together: <strong>never pass the inbound token through to upstream APIs.</strong> The MCP spec says plainly that servers must not accept or transit other tokens. Your server exchanges, looks up or mints its own upstream credential. If the upstream system and your MCP server share an authorization server, use a proper token exchange with a different audience, not the same bearer token.</p><h3>The connect flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*42qj1x753P1_sL44aMGWAA.jpeg" /></figure><p>In plain words:</p><ol><li>Claude calls your server without a token and gets 401 with a WWW-Authenticate header pointing to your Protected Resource Metadata (RFC 9728).</li><li>Claude discovers your authorization server, registers or identifies itself (Client ID Metadata Documents are now the preferred mechanism; Dynamic Client Registration is still supported but deprecated), and starts an OAuth 2.1 flow with PKCE.</li><li>The user consents. If your server also needs an upstream credential, this is where you chain the upstream consent, so the user sees one coherent connect experience.</li><li>Your authorization server issues a token to Claude, audience-bound to your MCP server.</li><li>Your backend stores the upstream refresh token in the secret manager and records a <strong>connection</strong> row that only holds a reference to it.</li></ol><p>Ask for the minimal scopes up front. The spec supports step-up authorization: when a tool needs more, your server responds with 403 and insufficient_scope, and the client can re-authorize with a wider set. Users trust a connector that asks for read access first far more than one that wants everything on day one.</p><h3>How to actually store tokens</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AWSXdHfve9K6_c7rT5fvCw.jpeg" /></figure><p>The pattern that has held up for me:</p><ul><li><strong>Secrets live in a secret manager</strong>: AWS Secrets Manager, Google Secret Manager, Azure Key Vault or HashiCorp Vault. Not in your application database, not in environment variables, and certainly not in logs.</li><li><strong>Your database stores references.</strong> The connections table has connection_id, user_id, tenant_id, provider, scopes, status, secret_ref, created_at, last_used_at. Never the token itself.</li><li><strong>Envelope encryption for scale.</strong> If you have hundreds of thousands of connections, storing each one as a separate vault secret gets expensive and slow. The alternative is to encrypt tokens with a data key, wrap that data key with a KMS key (per tenant if you can), and store the ciphertext. The KMS key never leaves the KMS; the plaintext token exists only in memory, briefly.</li><li><strong>Short-lived access tokens, cached in memory.</strong> Cache upstream access tokens in process memory (or an encrypted cache) until shortly before expiry. Persist only refresh tokens.</li><li><strong>Refresh under a lock.</strong> Two concurrent tool calls must not both refresh the same token. Many providers rotate refresh tokens on use, and a race will quietly invalidate the connection. Use a per-connection distributed lock, re-read after acquiring it, then refresh.</li><li><strong>Least-privilege access to the vault.</strong> Only the credential broker’s identity can read token secrets. Your tool code cannot. Your developers cannot, in production.</li><li><strong>Redact by default.</strong> Add a log filter that strips anything resembling a bearer token, and test that filter. Tokens leak through debug logs far more often than through breaches.</li><li><strong>Rotate and expire.</strong> Alert on connections whose refresh fails repeatedly, mark them needs_reauth, and tell the user through a clear tool error instead of failing silently.</li></ul><h3>Disconnect: the button nobody tests</h3><p>Connecting gets all the design attention. Disconnecting is where trust is won or lost, and where compliance auditors will look.</p><p>A user can disconnect in several ways: removing the connector in Claude, revoking access in your own settings page, revoking the app in the upstream system, or leaving the company and being deprovisioned. Your server has to handle all of them, and they all end in the same place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rFozOsN5MZ7fDYrwdLv4nQ.jpeg" /></figure><p>When a disconnect is triggered, from any direction:</p><ol><li><strong>Mark the connection </strong>revoking so new tool calls fail fast with a clear message.</li><li><strong>Revoke upstream.</strong> Call the provider’s revocation endpoint (RFC 7009 where supported) for the refresh token and any live access tokens.</li><li><strong>Delete the secret.</strong> Remove the vault secret or destroy the wrapped data key. If you use per-connection data keys, destroying the key is crypto-shredding: the ciphertext is now useless even in backups.</li><li><strong>Purge caches.</strong> In-memory access tokens, cached tool results, anything keyed by the connection.</li><li><strong>Invalidate inbound tokens.</strong> Revoke or deny-list the tokens your authorization server issued to Claude for this user and connector, so the next call gets a 401 and Claude prompts to reconnect.</li><li><strong>Cancel pending work.</strong> Drafts, export handles, scheduled jobs tied to this connection.</li><li><strong>Write the audit record</strong> and mark the connection revoked. Keep the metadata row for audit; drop everything sensitive.</li></ol><p>Make the whole sequence <strong>idempotent</strong> and <strong>retryable</strong>. Revocation endpoints fail, networks drop, and a disconnect that half-happened is worse than one that never started. Run it as a job with retries, and run a nightly sweeper that finds connections stuck in revoking, connections whose refresh token was rejected upstream, and connections unused for longer than your retention policy.</p><p>Then actually test it. Connect, call a tool, disconnect from each entry point, and assert that the next call fails, the secret is gone and the audit trail is complete. That test is the one I would make a release gate.</p><h3>A rollout checklist</h3><p>If you are about to start, this is the order I would do it in:</p><ol><li>Pick three to five tasks that people do every week and that currently require jumping between systems. Design tools for those, not for your API surface.</li><li>Write the rule set for each tool before writing the code, and get the business owner to review it.</li><li>Stand up the server with the layering above, the official SDK, Streamable HTTP and a stateless design.</li><li>Implement inbound token validation with audience checks on day one. Do not “add auth later”.</li><li>Put upstream credentials in a secret manager behind a credential broker, with refresh locking and log redaction.</li><li>Build disconnect as a first-class flow with a release-gate test.</li><li>Ship read-only tools first. Add write tools as drafts with explicit confirmation.</li><li>Instrument everything: audit logs with rule set versions, traces from tool call to upstream request, and dashboards for denials and refresh failures.</li></ol><h3>Closing thought</h3><p>The companies that will get real value out of assistants like Claude are not the ones with the most seats. They are the ones that sit down, decide what an assistant should be allowed to do in their business, and encode that once, carefully, in a connector.</p><p>It is unglamorous work. It is schemas, rule sets, vault policies and a disconnect test that nobody will ever praise. It is also the difference between an assistant that writes nice emails and one that can tell your operations lead exactly which orders are stuck, and why.</p><p><em>If you are building one of these and want to compare notes on rule sets or token custody, leave a response. I read all of them.</em></p><p><strong>References</strong> — Model Context Protocol specification, revision 2026–07–28: modelcontextprotocol.io/specification — MCP Authorization: modelcontextprotocol.io/specification/latest/basic/authorization — RFC 8707 (Resource Indicators), RFC 9728 (Protected Resource Metadata), RFC 7009 (Token Revocation)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3f7c6c85415" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PHP2Shell: Why Two Memory Bugs Put Most of the Web at Risk]]></title>
            <link>https://medium.com/@ferhatblnk/php2shell-why-two-memory-bugs-put-most-of-the-web-at-risk-4bf1202a46a5?source=rss-d2887a0d5055------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bf1202a46a5</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[vulnerability]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[information-security]]></category>
            <dc:creator><![CDATA[Ferhat Talha BULANIK]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 06:18:29 GMT</pubDate>
            <atom:updated>2026-10-22T06:19:04.257Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Two memory-safety bugs hiding in PHP’s error-handling paths since the PHP 5.4 era just became one of the biggest web vulnerabilities in years. Here is what went wrong, in plain terms.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C439BH0uXycNXAgdCPXaCQ.png" /></figure><h3>TL;DR</h3><p>On October 21, 2026, the PHP project shipped emergency fixes for two critical flaws, <strong>CVE-2026–109618</strong> and <strong>CVE-2026–109619</strong>, nicknamed <strong>PHP2Shell</strong>. Both are rated CVSS v4.0 9.2 and let an unauthenticated attacker run code on a web server.</p><ul><li><strong>Who is affected:</strong> every PHP setup that serves web requests: PHP-FPM, Apache mod_php, php-cgi, FrankenPHP and LiteSpeed. mod_php is the most exposed.</li><li><strong>Fix:</strong> upgrade to <strong>8.5.12, 8.4.27, 8.3.36 or 8.2.35</strong>, or your distro’s patched package.</li><li><strong>Urgency:</strong> Amazon saw an exploitation attempt on October 17, four days before disclosure, and now reports broad exploitation.</li></ul><p>PHP runs roughly 69% of websites whose server language is known, including WordPress, Drupal, Joomla and Magento. That reach is why this one matters.</p><h3>First, how PHP handles a request</h3><p>PHP looks stateless from the outside, but the interpreter underneath is long-lived C code. Both bugs live in the gap between those two pictures.</p><p>In every common setup, one worker process (an Apache child, an FPM worker) serves many requests in a row. For each request, PHP runs the same cycle:</p><ol><li><strong>Startup:</strong> set up per-request state: superglobals like $_POST and $_FILES, session data, upload buffers.</li><li><strong>Parse input:</strong> decode headers, form fields, multipart uploads. This happens before your application code runs.</li><li><strong>Execute:</strong> run the script.</li><li><strong>Cleanup:</strong> free per-request memory and reset globals so the worker is clean for the next visitor.</li></ol><p>The whole security model rests on step 4 being perfect. Each request must start from a clean slate, and cleanup must only touch data that was fully built. PHP2Shell breaks both assumptions.</p><h3>Bug 1: the half-built object (CVE-2026–109618)</h3><p><strong>In one line:</strong> running out of memory at the wrong moment leaves request data half-initialized, and cleanup then trusts it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ckd1TzkevpEY-o3y7tyU2g.png" /></figure><p>Same steps, different outcome: the abort skips the rest of the build, but cleanup still runs as if nothing happened.</p><p>PHP enforces a per-request memory_limit. When a request crosses it, PHP aborts with an out-of-memory (OOM) error and jumps straight to cleanup. That bail-out is normally safe.</p><p>The problem is <em>where</em> it can fire. If the OOM hits while PHP is in the middle of building an internal structure, say, while parsing a large or deeply nested request body, that structure is left with some fields set and others holding garbage. Cleanup does not know the build was interrupted. It walks the structure as if it were valid, frees pointers that were never real, and corrupts memory.</p><p>The dangerous part: the attacker controls the trigger. A crafted request can be sized to push PHP over its memory limit at precisely the right step. Memory corruption plus attacker-chosen timing is the classic recipe for code execution.</p><h3>Bug 2: the ghost from the last request (CVE-2026–109619)</h3><p><strong>In one line:</strong> a global pointer outlives the memory it points to, and the next request on the same worker uses it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L9Do6L7S8KbZ7XXUEqaKUw.png" /><figcaption>equest A’s cleanup frees the memory but forgets the global; request B then reads it before anything resets it.</figcaption></figure><p>This is a textbook <em>use-after-free</em>. Some request-owned internal state is referenced from a global variable. At the end of request A, the memory is freed, but the global still points at it.</p><p>When request B arrives on the same worker, PHP touches that stale pointer <em>before</em> its normal initialization resets it. By then the freed memory may hold anything, including bytes the attacker planted. The confirmed paths run through session upload progress tracking and, on PHP 8.5, fatal-error backtraces.</p><p>This bug also leaks. Researchers showed unauthenticated reads of worker memory, which can contain passwords, auth tokens and API keys from other users’ requests.</p><h3>So why did this happen?</h3><p>No single line of code is to blame. Four ordinary engineering realities lined up.</p><ol><li><strong>The interpreter is written in C.</strong> C has no guardrails against using freed memory or half-initialized structs. Every lifecycle rule is enforced by convention, and conventions slip.</li><li><strong>Error paths are the least-tested code.</strong> Happy paths run billions of times a day. The “out of memory halfway through parsing” path almost never runs, so its bugs survive for years. Calif traced the earliest affected code to PHP 5.4.0, released in 2012.</li><li><strong>“Shared-nothing” is a promise, not a wall.</strong> Developers think of each PHP request as isolated. Inside the worker, it is isolated only if cleanup and re-initialization are flawless. Bug 2 lives exactly in that gap.</li><li><strong>The exploit was too hard for humans, until it wasn’t.</strong> Wiz says the flaws had sat in the code for decades, but turning them into a working exploit took a chain of steps at the limit of what human researchers could do. Frontier AI models lowered that barrier. Calif, Wiz and OpenAI were credited for the research.</li></ol><h3>How it went public</h3><ul><li><strong>Oct 17:</strong> Amazon’s honeypots catch a PHP2Shell exploitation attempt, before any public disclosure.</li><li><strong>Oct 20:</strong> The CVE IDs leak in a Hacker News post. PHP publishes an advance notice the same day.</li><li><strong>Oct 21:</strong> PHP releases fixes at 14:00 UTC, a day earlier than planned. CISA urges immediate patching.</li></ul><p>The leaked post claimed a CVSS score of 10.0. The PHP Foundation says that figure was wrong; the official rating is 9.2.</p><h3>What to do right now</h3><p>Patching is the only complete fix. Everything else just narrows the attack surface.</p><ul><li><strong>PHP 8.5.x</strong> → upgrade to <strong>8.5.12</strong></li><li><strong>PHP 8.4.x</strong> → upgrade to <strong>8.4.27</strong></li><li><strong>PHP 8.3.x</strong> → upgrade to <strong>8.3.36</strong></li><li><strong>PHP 8.2.x</strong> → upgrade to <strong>8.2.35</strong></li><li><strong>PHP 7.4 to 8.1</strong> → no official release; apply PHP’s source backports or your vendor’s build</li><li><strong>PHP 5.4 to 7.3</strong> → end of life, no fix; upgrade or take the system offline</li></ul><p><strong>After patching:</strong></p><ul><li>Check the PHP that actually serves web traffic, not just php -v on the CLI; they can be different installs.</li><li>Restart every PHP worker or redeploy containers so no process runs the old build.</li><li>Distro packages may keep an older version number with backported fixes. Check your vendor’s advisory.</li><li>Investigate logs from at least October 17, not from the disclosure date.</li></ul><p><strong>If you cannot patch today</strong>, PHP lists interim settings that block known paths, applied server-side and followed by a worker restart: memory_limit=-1 enforced so apps cannot override it (Bug 1), session.upload_progress.enabled=0 (Bug 2), and fatal_error_backtraces=0 on PHP 8.5. Cloudflare has also pushed WAF rules to all plans. Treat both as stopgaps, and consider isolating unpatchable systems, as the UK NCSC and CERT-EU advise.</p><h3>The bigger lesson</h3><p>PHP2Shell is not about a careless commit. It is about old C code, rarely exercised error paths, and an isolation model that only holds if cleanup is perfect. AI-assisted research is now making those dusty corners exploitable, so expect more bugs like this across mature runtimes. The long tail of forgotten, unpatched PHP installs will keep this one alive for a while. Patch, restart, verify.</p><h3>Sources</h3><ul><li><a href="https://www.php.net/archive/2026.php#2026-10-21-5">PHP security advisory, Oct 21, 2026</a></li><li><a href="https://github.com/php/php-src/security/advisories/GHSA-w8hw-w9fx-j79w">GHSA-w8hw-w9fx-j79w: RCE via OOM corruption</a></li><li><a href="https://github.com/php/php-src/security/advisories/GHSA-6wmf-4rv5-p3rp">GHSA-6wmf-4rv5-p3rp: RCE via stale global state</a></li><li><a href="https://www.tenable.com/blog/php2shell-cve-2026-109618-cve-2026-109619-frequently-asked-questions-about-critical-php-remote">Tenable: php2shell FAQ</a></li><li><a href="https://blog.qualys.com/vulnerabilities-threat-research/2026/10/20/php-announces-critical-security-release-for-two-vulnerabilities">Qualys: PHP2Shell patches and mitigations</a></li><li><a href="https://www.helpnetsecurity.com/2026/10/21/php2shell-php-vulnerabilities-patched-cve-2026-109618-cve-2026-109619/">Help Net Security: PHP2Shell patched</a></li><li><a href="https://www.cisa.gov/news-events/alerts/2026/10/21/critical-vulnerabilities-php-require-immediate-patching">CISA alert</a></li><li><a href="https://calif.io/php2shell/">Calif: php2shell technical writeup</a></li><li><a href="https://www.wiz.io/blog/php2shell-php-rce">Wiz: PHP2Shell research</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bf1202a46a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your code reads secrets from Vault. What do you test it against?]]></title>
            <link>https://medium.com/@ferhatblnk/your-code-reads-secrets-from-vault-what-do-you-test-it-against-349fbe78c2e0?source=rss-d2887a0d5055------2</link>
            <guid isPermaLink="false">https://medium.com/p/349fbe78c2e0</guid>
            <category><![CDATA[hashicorp-vault]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[testcontainer]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Ferhat Talha BULANIK]]></dc:creator>
            <pubDate>Thu, 08 Oct 2026 13:08:44 GMT</pubDate>
            <atom:updated>2026-10-08T13:08:44.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gj6meMhnihCa33DViiER7A.png" /></figure><p>I wrote a small package that starts and stops a real Vault from inside .NET tests. Here is what it does, and three things that surprised me along the way.</p><p>On a team that keeps its secrets in HashiCorp Vault, the code that reads those secrets is some of the most critical code in the application. Read from the wrong path and the service does not start. Miss a permission and somebody’s phone rings at night. Yet when it comes to tests, this is often the least tested part.</p><p>The reason is simple: there is no Vault in the test environment. So either someone writes a fake class that imitates Vault, or that part is not tested at all. The trouble with a fake is that it behaves the way you wrote it, not the way Vault behaves. A wrong path, a token without permission, an encryption engine that was never enabled: the fake knows none of it. Tests stay green and the error shows up in production.</p><p>There is a well-known fix: Testcontainers. It starts the real service in Docker from inside the test and removes it when the test ends. It has ready-made modules for PostgreSQL, Redis, RabbitMQ. It has one for Vault too, in Java, Go, Node.js and Python. Not in .NET. If you wanted to test against Vault in .NET, you wrote the image, the port, the token, the wait-until-ready loop and the run-a-command-inside part by hand. The same thirty or forty lines in every project.</p><p>So I wrote the missing piece. It is called Drydock.Testcontainers.Vault. It is <a href="https://www.nuget.org/packages/Drydock.Testcontainers.Vault">on NuGet</a>, <a href="https://github.com/ferhatblnk/drydock-testcontainers-vault">open source on GitHub</a>, and MIT licensed.</p><h3>What it does</h3><pre>await using var vault = new VaultBuilder(&quot;hashicorp/vault:2.1&quot;)<br>    .WithInitCommand(&quot;kv put secret/orders-api connection=Host=db&quot;)<br>    .Build();<br><br>await vault.StartAsync();</pre><p>When StartAsync returns, three things are true. Vault is up and answering. The root token is known. And the secret your test needs is already there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*baSmRieTrmifDDhO9ZhzTg.png" /></figure><p>From there you point your client at vault.GetBaseAddress(), authenticate with vault.GetRootToken(), and test against the real thing. I use VaultSharp in my own tests, but the package depends only on Testcontainers, so any client works. When the test ends, the container is gone.</p><p>WithInitCommand takes ordinary Vault CLI commands, the ones you already know from the documentation: enable an engine, create a key, write a policy, set up AppRole. They run in order once the server is ready.</p><p>Change the image name to openbao/openbao:2.7 and the same code runs OpenBao, the open-source fork of Vault.</p><h3>A permission nobody needed</h3><p>The first surprise came from reading the Java and Go modules. Both ask Docker for an extra Linux capability called IPC_LOCK when they start Vault. It is there because Vault&#39;s documentation says so: it lets Vault lock its memory, so secrets never get swapped to disk.</p><p>I checked what actually happens. In dev mode, which is what every test uses, Vault does not lock memory at all. The startup log says Mlock: supported: true, enabled: false, in every version I tried from 1.13 to 2.1. The capability is requested for nothing.</p><p>And it is not free. Some CI services refuse to start a container that asks for extra capabilities. There is <a href="https://github.com/testcontainers/testcontainers-java/issues/6623">an issue on the Java module</a> from someone whose Vault container would not start for exactly this reason. It was closed without a fix.</p><p>My module does not ask for it.</p><h3>A setup error should not pass quietly</h3><p>The second surprise was what happens when one of those setup commands fails. Say you misspell the name of an engine.</p><p>In the Java module the failure is written to the log and the start carries on. Your container counts as ready, the test begins, and it fails three steps later with an error that has nothing to do with the real cause.</p><p>Here the commands run in one shell call that stops at the first failure, and StartAsync throws with Vault&#39;s own words:</p><pre>The Vault init commands failed with exit code 2: Error enabling: Error making API request.<br><br>URL: POST http://127.0.0.1:8200/v1/sys/mounts/no-such-engine<br>Code: 400. Errors:<br><br>* plugin not found in the catalog: no-such-engine</pre><p>The commands after the failing one do not run. The test fails at the cause.</p><p>A smaller one in the same spirit: Vault refuses a root token that contains a period, and the way it refuses is to exit with invalid request in its log. The builder now says so before any container starts.</p><h3>The big one: modules break when Testcontainers is updated</h3><p>This is the surprise that changed the design.</p><p>A Testcontainers module is a small library compiled against the Testcontainers core. Every module creates its configuration through one particular constructor in the core, a constructor whose parameters are all optional. When the maintainers add a parameter to it, your source code still compiles. But a module that was compiled earlier is now looking for a constructor that no longer exists. It fails at run time with MissingMethodException, on the very first new SomethingBuilder(...).</p><p>I did not want to take that on faith, so I compiled a minimal module against one version of the core and ran it with another:</p><ul><li>Built against 4.0, run with 4.6: works.</li><li>Built against 4.0, run with 4.7: MissingMethodException.</li><li>Built against 4.7, run with 4.8: MissingMethodException.</li><li>Built against 4.9, run with 4.10: MissingMethodException.</li></ul><p>Three breaks between August 2025 and January 2026. The official modules break the same way: the official Redis module from 4.9 throws the same exception on core 4.15. It is not a problem for them, because they are released together with the core, and the release notes say to keep every Testcontainers package on the same version.</p><p>A package that is released on its own cannot do that. Every time the core changed that constructor, my users would be stuck until I shipped a new build.</p><p>The fix turned out to be small. Instead of calling that constructor directly, the module finds it at run time, as “the constructor whose parameters are all optional”, and calls it with the default values:</p><pre>var constructor = typeof(ContainerConfiguration)<br>    .GetConstructors()<br>    .OrderBy(candidate =&gt; candidate.GetParameters().Length)<br>    .First(candidate =&gt; Array.TrueForAll(candidate.GetParameters(), parameter =&gt; parameter.IsOptional));<br><br>var arguments = Array.ConvertAll(constructor.GetParameters(), parameter =&gt; parameter.DefaultValue);<br><br>return (ContainerConfiguration)constructor.Invoke(arguments);</pre><p>Then I repeated the experiment. Built against 4.0, a module written this way started a container with 4.6, 4.7, 4.8, 4.10 and 4.15. The published package also passes its whole test suite against the unreleased development build of the core. CI runs the suite against the newest release every week, so if a future change breaks it, I find out before the users do.</p><p>One more lesson from the same corner. I wanted to require as old a Testcontainers version as I could, so that nobody would be forced to upgrade. NuGet talked me out of it: every 4.x version before 4.14 depends on an SSH.NET release with known vulnerabilities. Anyone installing my package into a fresh project would have been greeted by a high-severity security warning. So the minimum is 4.14.</p><h3>Publishing without a key</h3><p>A short note on publishing, because it is fairly new and I liked it.</p><p>NuGet has something called Trusted Publishing. You tell nuget.org which GitHub repository and which workflow file may publish for you. At publish time the workflow asks for a key and gets one that lives for an hour. There is no API key to create, to store in a secret, or to leak.</p><p>My first two attempts failed with “no matching trust policy”. I had filled in the form on nuget.org and never pressed Create. The third one went through.</p><h3>If you want to try it</h3><p>You need Docker running, then:</p><pre>dotnet add package Drydock.Testcontainers.Vault</pre><p>In an xUnit test class it looks like this:</p><pre>public sealed class OrdersApiTest : IAsyncLifetime<br>{<br>    private readonly VaultContainer _vault = new VaultBuilder(&quot;hashicorp/vault:2.1&quot;)<br>        .WithInitCommand(&quot;secrets enable transit&quot;, &quot;write -f transit/keys/orders&quot;)<br>        .WithInitCommand(&quot;kv put secret/orders-api connection=Host=db&quot;)<br>        .Build();<br><br>    public async ValueTask InitializeAsync() =&gt; await _vault.StartAsync();<br><br>    public ValueTask DisposeAsync() =&gt; _vault.DisposeAsync();<br>}</pre><p>The README has more recipes: writing a policy, logging in with AppRole, reaching Vault from another container. Each of them has a test in the repository.</p><h3>What it does not do</h3><p>It is version 0.1, so a few things to know:</p><ul><li>It is for dev mode only. The server keeps everything in memory and speaks plain HTTP. That is what makes it fast and disposable, and it is why this is a tool for tests and nothing else.</li><li>Setup commands run after every start. If you reuse a container between runs, use commands that can run twice.</li><li>Linux containers only. The tests run on .NET 8, 9 and 10.</li></ul><p>The package is here: <a href="https://www.nuget.org/packages/Drydock.Testcontainers.Vault">nuget.org/packages/Drydock.Testcontainers.Vault</a>. The code is here: <a href="https://github.com/ferhatblnk/drydock-testcontainers-vault">github.com/ferhatblnk/drydock-testcontainers-vault</a>.</p><p>I have also <a href="https://github.com/testcontainers/testcontainers-dotnet/issues/1789">offered the module</a> to the official Testcontainers for .NET repository. If they take it, it will move there. Until then it lives here, and issues and pull requests are welcome.</p><p>One last thing. I built this with an AI coding assistant, which is part of why I leaned so hard on measurements and tests. Everything I claim in this post is something that was run, not something that was assumed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=349fbe78c2e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A sync job is not a cron job. It took us three bugs to see it.]]></title>
            <link>https://medium.com/@ferhatblnk/a-sync-job-is-not-a-cron-job-it-took-us-three-bugs-to-see-it-2a3ccb35c362?source=rss-d2887a0d5055------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a3ccb35c362</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[quartz]]></category>
            <category><![CDATA[hangfire]]></category>
            <category><![CDATA[scheduling]]></category>
            <dc:creator><![CDATA[Ferhat Talha BULANIK]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 12:56:03 GMT</pubDate>
            <atom:updated>2026-11-17T08:15:10.451Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lov2G_BMFDoOtz68Wjpp_A@2x.png" /></figure><p>I wrote a small scheduler where every sync job is a row in Postgres, with its own window and its own cursor. This is how it works and why I built it the way I did.</p><p>Türkçesi: Sync job, cron job değildir. Biz bunu üç bug’la öğrendik.</p><p>If your application pulls data from somebody else’s API, it probably started the way they all do. A timer fires every night, a method fetches “everything since yesterday”, and that’s it.</p><p>Then a customer connects an account with two years of orders in it. The first sync runs for hours, a deploy kills it near the end, and it starts over from the beginning. While that’s going on the API begins to answer 429, because a second worker picked up another job for the same account and the two are now spending the same rate limit.</p><p>None of that is a scheduling problem. The timer fired on time. What’s missing is everything about the job itself: which range it covers, how far it got, how often it failed and why, and which other job must not run next to it.</p><p>I work on a project that syncs orders and products from external APIs for a lot of accounts. We got this wrong in a few interesting ways, fixed them one by one, and ended up with a design I’m happy with. I rewrote that design as a small library so it doesn’t stay buried in one codebase. It’s called SyncLane, and it’s open source on GitHub under the Apache 2.0 license.</p><h3>Why not just use a scheduler</h3><p>Hangfire and Quartz are good at what they do, and I’d still reach for them for “send this email at nine”. But a sync job carries state that a general scheduler knows nothing about, so you end up keeping it on the side: in serialized arguments, in a table of your own next to the scheduler’s, in a distributed lock. When something gets stuck, the answer to “why” is spread over three places.</p><p>I wanted the opposite. One table, one row per job, and everything about the job on that row. If something is stuck I want to find out with a SELECT and fix it with an UPDATE.</p><h3>Everything is on the row</h3><p>This is a job from the demo, trimmed to the columns that matter here:</p><pre>id              | 33<br>owner           | globex<br>type            | orders<br>status          | failed<br>window_start    | 2026-08-08<br>window_end      | 2026-09-07<br>cursor          | 50<br>processed_count | 50<br>attempt_count   | 4<br>error           | InvalidOperationException: The shop returned a page that could not be read.<br>next_run_at     | 2026-10-07 12:15:50</pre><p>One month of one account’s orders. The second page keeps failing, so the job has handled 50 records, is on its fourth attempt, and will try again at next_run_at. From cursor 50, not from the start.</p><p>History is cut into slices like this one, and every slice is its own job. Two years of orders become 25 small jobs instead of one enormous one. They run newest first, so the customer sees last month within minutes while the older months load behind it.</p><p>What’s new gets a job of its own every few minutes. Its window starts where the previous one ended, minus a small overlap for records that show up late. If the whole system is down for three days, the next job simply has a three-day window. There’s nothing to catch up by hand.</p><p>The cursor is saved after every page. Deploy, crash or timeout, the job continues from the last page it finished.</p><h3>One account, one job at a time</h3><p>A rate limit belongs to an account, not to your worker. So the jobs of one account have to run one after the other, while different accounts run side by side. I call that a lane. Usually a lane is one account. If two of your accounts belong to the same seller and share a limit, they share a lane.</p><p>The question is how you guarantee that when ten workers ask for work at the same moment. The query that picks the next job skips any lane that already has a running job, and that looks like enough. It isn’t. Two workers can ask in the same millisecond, each picks a different job of the same lane, and neither sees the other because neither has committed yet.</p><p>The first instinct is a lock. We had one for a while and I never liked it. A lock is something you have to remember to take, and something a dead process can keep holding.</p><p>What replaced it is one statement:</p><pre>CREATE UNIQUE INDEX jobs_one_running_per_lane<br>    ON jobs (queue, lane) WHERE status = &#39;running&#39;;</pre><p>At most one running row per lane, and the database enforces it. The second worker’s update is refused, it asks again, and this time it sees that the lane is taken.</p><p>I wanted to know whether this mattered in practice or only on paper, so I dropped the index and ran 24 workers against 3 lanes. Over 600 jobs, two jobs of the same lane ran together 170 times. With the index back it was zero.</p><h3>Three bugs in the planner</h3><p>Something has to decide which jobs exist. It’s the part that looks easiest and it’s where we lost the most time. All three of these were live at some point.</p><p>The first was a shortcut. The planner began with a check: if this account already has its initial jobs, return. That was fine until we raised the history from 60 days to two years. New accounts got two years. Every account that was already connected stayed at 60 days, because the check said “already planned”. Nothing failed. Some reports were just empty for the older accounts.</p><p>The second was the reason the first existed. The slices were generated starting from the current time, so calling the planner an hour later produced slices shifted by an hour. They didn’t match the ones in the table and would have gone in as duplicates. The early return was hiding that. The order of the fix mattered: first anchor the slices to midnight UTC, so the same call always produces the same slices, and only then remove the early return.</p><p>The third took the longest to notice. The daily “what’s new” job also had a window, so we spotted duplicates the same way as for history: same window start, skip it. That window start came from the data, the latest update we had stored minus five minutes. On a day when an account had nothing new, the value didn’t move. The next day the planner computed the same window start, called it a duplicate and skipped it. Same the day after. That account never got a daily job again. Six accounts stopped like this, one after the other over a few weeks, and each of them looked alive, because the last run had re-read a couple of records at the boundary and reported a count above zero.</p><p>What came out of it fits in one sentence. The planner compares what should exist with what exists, adds only the difference, and has to be safe to call any number of times. No flag that says “I already ran”. A history slice is unique by its window, a recurring job is unique by its period, and a unique index backs both, so two instances planning at the same moment still create every job once.</p><p>There’s a test for the first bug now. Raise the history from 60 days to two years, and the planner adds exactly 23 slices, the gap. Call it again and it adds nothing.</p><h3>When a job keeps failing</h3><p>A failed job waits and tries again, and the wait doubles each time. A 429 gets a longer wait than an ordinary error. That part is standard.</p><p>The less obvious part is what to do when the attempts run out. Keep retrying, and one broken month of history holds up everything behind it in the lane, today’s data included. Give up right away, and you lose jobs that only failed because the lane was crowded and throttled.</p><p>So there’s a status in between, called deferred. The job steps aside, the rest of the lane finishes, and then it gets one more attempt with the lane to itself. If that fails too it’s abandoned, and it stays there with its cursor and its error until someone requeues it.</p><p>One more thing we learned the hard way. A lane used to move on when the lease of its running job had expired, on the theory that the worker must be dead. Then an account got throttled, pages started taking around nine minutes each with all the waiting, the lease was ten, and sooner or later one ran over while the worker was perfectly alive. Another worker saw a free lane, took that account’s next job, and now two workers were pushing on an API that was already saying “slow down”.</p><p>Today a lane is closed for as long as it has a running row. An expired lease lets you do exactly one thing, take over that same job. And a heartbeat renews the lease while a slow page is in flight, so a slow page no longer looks like a dead worker.</p><h3>What you write</h3><p>A handler does one page and says where the next one starts:</p><pre>public sealed class OrderHandler(ShopApi api, OrderStore store) : IJobHandler<br>{<br>    public async Task&lt;JobPage&gt; RunPageAsync(Job job, CancellationToken ct)<br>    {<br>        var page = await api.GetOrdersAsync(job.Owner, job.WindowStart, job.WindowEnd, job.Cursor, ct);<br>        await store.UpsertAsync(page.Orders, ct);<br><br>        return new JobPage(page.NextCursor, page.Orders.Count);<br>    }<br>}</pre><p>The only thing I ask of it is to write with upserts. A page can arrive twice: after a crash between your write and the cursor save, and in the overlap between two windows.</p><p>The rest is saying what should exist:</p><pre>queue.Snapshot&lt;ProductHandler&gt;(&quot;products&quot;, every: TimeSpan.FromDays(1));<br><br>queue.Windowed&lt;OrderHandler&gt;(&quot;orders&quot;,<br>    horizon: TimeSpan.FromDays(730),<br>    slice: TimeSpan.FromDays(30),<br>    every: TimeSpan.FromMinutes(15),<br>    overlap: TimeSpan.FromMinutes(5));</pre><p>A word about slice, because we got that wrong as well. At one point we tripled it from 30 to 90 days to have fewer jobs. For the biggest account a single slice became 43,000 records, 430 pages, about twenty hours of requests, against page tokens that live for twenty-four. Any hiccup late in a slice cost most of a day. A slice is the largest piece of work that can’t be split, so keep it small.</p><h3>If you want to try it</h3><p>There’s a demo in the repo. It starts Postgres and a small app that syncs four pretend shop accounts. The pretend shop is slow, sometimes answers 429 or 503, and one page of one account is broken on purpose.</p><pre>git clone https://github.com/ferhatblnk/synclane<br>cd synclane<br>docker compose up --build</pre><p>Then open <a href="http://localhost:8080.">http://localhost:8080.</a> Two accounts that share a lane take turns while the others run next to them. Orders arrive from the most recent month backwards. Failed jobs come back from their cursors. One job goes through failed, deferred and abandoned; press Requeue and it finishes from cursor 50. Run docker compose restart demo in the middle of it all, and the running jobs go back to pending and carry on after the restart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JogvnBpeFjhiB8KRtTZ2iA.png" /></figure><p>You don’t need the page, though. The table is right there:</p><pre>docker compose exec postgres psql -U postgres -d synclane \<br>  -c &quot;select id, owner, type, status, cursor, attempt_count, error from synclane.jobs&quot;</pre><p>That’s really the point of the whole thing.</p><h3><strong>Where it stands now</strong></h3><p>When I wrote this, it was version 0.1. It’s at 0.6 now. The design in this post hasn’t changed; what came later sits on top of it:</p><ul><li>It’s on NuGet: dotnet add package SyncLane.</li><li>Workers hear about new jobs through LISTEN/NOTIFY, behind PgBouncer too, and poll when they can’t.</li><li>Rate budgets: requests to one account go out at a declared pace shared by every worker, and a 429 slows that account down everywhere.</li><li>Recipes: for an API that lists JSON page by page, a small JSON file replaces the handler, and an AI assistant can write it from a curl.</li><li>A monitor API with HTTP endpoints, health checks, priorities, sync-now and ordered queues.</li><li>After a takeover, every write is fenced by the lease itself, not only by the worker’s name. Thanks to Tim Urista for the comment that led to it.</li></ul><p>Some things still hold. The design has run in production for a long time, but this code hasn’t yet, so try it on something that is allowed to fail. It only works with PostgreSQL, and a job still has no custom arguments. Everything that changed is in the <a href="https://github.com/ferhatblnk/synclane/blob/main/CHANGELOG.md">changelog</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a3ccb35c362" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sync job, cron job değildir. Biz bunu üç bug’la öğrendik.]]></title>
            <link>https://medium.com/@ferhatblnk/sync-job-cron-job-de%C4%9Fildir-biz-bunu-%C3%BC%C3%A7-bugla-%C3%B6%C4%9Frendik-3a9afddc53ee?source=rss-d2887a0d5055------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a9afddc53ee</guid>
            <category><![CDATA[quartz]]></category>
            <category><![CDATA[hangfire]]></category>
            <category><![CDATA[scheduling]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Ferhat Talha BULANIK]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 12:52:13 GMT</pubDate>
            <atom:updated>2026-11-17T08:16:51.147Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lov2G_BMFDoOtz68Wjpp_A@2x.png" /></figure><p>Her sync job’un Postgres’te bir satır olduğu, kendi penceresini ve cursor’ını taşıdığı küçük bir scheduler yazdım. Nasıl çalıştığını ve neden böyle kurduğumu anlatıyorum.</p><p>English version: A sync job is not a cron job. It took us three bugs to see it.</p><p>Uygulaman başka birinin API’sinden veri çekiyorsa büyük ihtimalle herkes gibi başlamışsındır. Her gece bir timer çalışır, bir metot “dünden beri ne varsa” çeker, iş biter.</p><p>Sonra bir müşteri içinde iki yıllık sipariş olan bir hesap bağlar. İlk senkronizasyon saatlerce sürer, sonuna yakın bir deploy gelir ve iş baştan başlar. Bu arada API 429 dönmeye başlar, çünkü ikinci bir worker aynı hesabın başka bir işini almıştır ve ikisi aynı rate limit’i harcıyordur.</p><p>Bunların hiçbiri zamanlama sorunu değil. Timer tam vaktinde çalıştı. Eksik olan, işin kendisiyle ilgili her şey: hangi aralığı kapsıyor, nereye kadar geldi, kaç kere patladı ve neden, yanında hangi iş çalışmamalı.</p><p>Çok sayıda hesap için dış API’lerden sipariş ve ürün çeken bir projede çalışıyorum. Bu işi birkaç ilginç şekilde yanlış yaptık, tek tek düzelttik ve sonunda içime sinen bir tasarıma vardık. O tasarım tek bir kod tabanında gömülü kalmasın diye küçük bir kütüphane olarak yeniden yazdım. Adı SyncLane. GitHub’da açık kaynak, Apache 2.0 lisanslı.</p><h3>Neden hazır bir scheduler değil</h3><p>Hangfire ve Quartz yaptıkları işi iyi yapıyor, hakkını vermek lazım. “Şu maili dokuzda gönder” için yine onları kullanırım. Ama bir sync job’un, genel bir scheduler’ın hiç bilmediği bir durumu var. O durumu da ister istemez kenarda bir yerde tutuyorsun: serialize edilmiş argümanlarda, scheduler’ın tablosunun yanına açtığın kendi tablonda, bir distributed lock’ta. Bir şey takıldığında “neden” sorusunun cevabı üç ayrı yere dağılmış oluyor.</p><p>Ben tersini istedim. Tek tablo, her iş için tek satır, işle ilgili her şey o satırda. Bir şey takılmışsa bir SELECT ile öğrenebileyim, bir UPDATE ile düzeltebileyim.</p><h3>Her şey satırın üstünde</h3><p>Demodan bir iş, konuyla ilgili kolonlarıyla:</p><pre>id              | 33<br>owner           | globex<br>type            | orders<br>status          | failed<br>window_start    | 2026-08-08<br>window_end      | 2026-09-07<br>cursor          | 50<br>processed_count | 50<br>attempt_count   | 4<br>error           | InvalidOperationException: The shop returned a page that could not be read.<br>next_run_at     | 2026-10-07 12:15:50</pre><p>Bir hesabın bir aylık siparişleri. İkinci sayfa sürekli patlıyor. İş 50 kayıt işlemiş, dördüncü denemesinde ve next_run_at geldiğinde tekrar deneyecek. Baştan değil, cursor 50’den.</p><p>Geçmiş böyle dilimlere bölünüyor ve her dilim ayrı bir iş. İki yıllık sipariş, tek bir dev iş yerine 25 küçük iş oluyor. En yeniden eskiye doğru çalışıyorlar. Müşteri geçen ayı birkaç dakika içinde görüyor, eski aylar arkadan yükleniyor.</p><p>Yeni gelenler için birkaç dakikada bir ayrı bir iş açılıyor. Penceresi bir öncekinin bittiği yerden başlıyor, geç düşen kayıtlar için küçük bir örtüşmeyle. Sistem üç gün kapalı kalsa bir sonraki işin penceresi üç günlük oluyor, o kadar. Elle telafi edilecek bir şey yok.</p><p>Cursor her sayfadan sonra kaydediliyor. Deploy da olsa, çökme de olsa, timeout da olsa iş bitirdiği son sayfadan devam ediyor.</p><h3>Bir hesap, aynı anda tek iş</h3><p>Rate limit senin worker’ına değil, hesaba ait. O yüzden bir hesabın işleri sırayla çalışmalı, farklı hesaplar ise yan yana. Ben buna lane diyorum, yani şerit. Çoğu zaman bir şerit bir hesap demek. İki hesabın aynı satıcıya aitse ve limiti paylaşıyorsa şeridi de paylaşıyorlar.</p><p>Asıl soru şu: on worker aynı anda iş isterken bunu nasıl garanti edersin? Sıradaki işi seçen sorgu, çalışan işi olan şeritleri atlıyor. Yeterli gibi duruyor ama değil. İki worker aynı milisaniyede sorar, her biri aynı şeridin farklı bir işini seçer ve birbirini görmez, çünkü ikisi de henüz commit etmemiştir.</p><p>İlk refleks bir lock koymak. Bir süre bizde de vardı ve hiç içime sinmedi. Lock, almayı unutmaman gereken bir şey. Üstelik ölmüş bir process’in elinde de kalabiliyor.</p><p>Yerine gelen şey tek bir ifade:</p><pre>CREATE UNIQUE INDEX jobs_one_running_per_lane<br>    ON jobs (queue, lane) WHERE status = &#39;running&#39;;</pre><p>Şerit başına en fazla bir running satır, ve bunu veritabanı sağlıyor. İkinci worker’ın update’i reddediliyor, tekrar soruyor ve bu sefer şeridin dolu olduğunu görüyor.</p><p>Bunun pratikte mi önemli olduğunu yoksa sadece kâğıt üstünde mi durduğunu merak ettim. Index’i silip 3 şeride karşı 24 worker çalıştırdım. 600 işte, aynı şeridin iki işi 170 kere aynı anda çalıştı. Index’i geri koyunca sıfır.</p><h3>Planlayıcıdaki üç bug</h3><p>Hangi işlerin var olacağına birinin karar vermesi lazım. En kolay görünen kısım bu ve en çok vakti burada kaybettik. Üçü de bir dönem canlıdaydı.</p><p>Birincisi bir kestirmeydi. Planlayıcı bir kontrolle başlıyordu: bu hesabın ilk yükleme işleri zaten varsa çık. Geçmişi 60 günden iki yıla çıkarana kadar sorun yoktu. Yeni hesaplar iki yıl aldı. Zaten bağlı olan bütün hesaplar 60 günde kaldı, çünkü kontrol “zaten planlandı” diyordu. Hiçbir şey hata vermedi. Sadece eski hesaplarda bazı raporlar boş geliyordu.</p><p>İkincisi, birincinin var olma sebebiydi. Dilimler o anki saatten başlayarak üretiliyordu, yani planlayıcıyı bir saat sonra çağırınca dilimler bir saat kaymış çıkıyordu. Tablodakilerle eşleşmedikleri için kopya olarak eklenirlerdi. Baştaki kontrol aslında bunu örtüyordu. Düzeltmenin sırası önemliydi: önce dilimleri UTC gece yarısına sabitle ki aynı çağrı hep aynı dilimleri üretsin, kontrolü ondan sonra kaldır.</p><p>Üçüncüsünü fark etmek en uzun sürdü. Günlük “yeni ne var” işinin de bir penceresi vardı, biz de kopyayı geçmiştekiyle aynı şekilde ayıklıyorduk: pencere başlangıcı aynıysa atla. O başlangıç veriden geliyordu, elimizdeki en son güncelleme eksi beş dakika. Bir hesaba yeni hiçbir şey gelmediği gün bu değer yerinde kaldı. Ertesi gün planlayıcı aynı başlangıcı hesapladı, kopya dedi, atladı. Sonraki gün yine. O hesaba bir daha günlük iş açılmadı. Altı hesap birkaç hafta içinde sırayla böyle durdu. Hepsi de canlı görünüyordu, çünkü son çalışma sınırdaki birkaç kaydı yeniden okumuş ve sıfırdan büyük bir sayı raporlamıştı.</p><p>Bundan çıkan kural tek cümle: planlayıcı olması gerekenle var olanı karşılaştırır, yalnızca farkı ekler ve kaç kere çağrılırsa çağrılsın güvenli olmak zorundadır. “Ben zaten çalıştım” diyen bir bayrak yok. Geçmiş dilimi penceresiyle tekil, tekrarlayan iş dönemiyle tekil. İkisinin de arkasında bir unique index var, yani iki instance aynı anda planlasa bile her iş bir kere açılıyor.</p><p>İlk bug için artık bir test var. Geçmişi 60 günden iki yıla çıkarıyorsun, planlayıcı tam 23 dilim ekliyor, yani sadece boşluğu. Bir daha çağırıyorsun, hiçbir şey eklemiyor.</p><h3>Bir iş sürekli patlarsa</h3><p>Patlayan iş bekleyip tekrar deniyor, bekleme her seferinde ikiye katlanıyor. 429 alan iş normal bir hatadan daha uzun bekliyor. Buraya kadarı bildiğimiz şeyler.</p><p>Asıl mesele denemeler bitince ne olacağı. Denemeye devam edersen geçmişin bozuk bir ayı, şeritte arkasındaki her şeyi tutar, bugünün verisi dahil. Hemen vazgeçersen, sırf şerit kalabalık ve throttle altında olduğu için patlamış işleri kaybedersin.</p><p>O yüzden arada bir durum daha var: deferred. İş kenara çekiliyor, şeridin geri kalanı bitiyor, sonra şerit tamamen ona kalmışken bir deneme hakkı daha alıyor. O da patlarsa abandoned oluyor ve biri yeniden kuyruğa alana kadar cursor’ı ve hatasıyla orada duruyor.</p><p>Bir şeyi daha zor yoldan öğrendik. Eskiden bir şeritte çalışan işin lease’i dolunca şerit yoluna devam ediyordu, worker ölmüştür diye. Sonra bir hesap throttle yedi, bekleme ve tekrarlarla sayfalar dokuzar dakika sürmeye başladı, lease on dakikaydı ve bir noktada worker gayet hayattayken lease doldu. Başka bir worker şeridi boş gördü, o hesabın sıradaki işini aldı. Artık iki worker, zaten “yavaşla” diyen bir API’ye yükleniyordu.</p><p>Bugün bir şerit, içinde running bir satır olduğu sürece kapalı. Dolmuş bir lease tek bir şeye izin veriyor: aynı işi devralmaya. Yavaş bir sayfa sürerken de bir heartbeat lease’i yeniliyor, yani yavaş sayfa artık ölü worker gibi görünmüyor.</p><h3>Sen ne yazıyorsun</h3><p>Handler bir sayfa işliyor ve bir sonrakinin nereden başladığını söylüyor:</p><pre>public sealed class OrderHandler(ShopApi api, OrderStore store) : IJobHandler<br>{<br>    public async Task&lt;JobPage&gt; RunPageAsync(Job job, CancellationToken ct)<br>    {<br>        var page = await api.GetOrdersAsync(job.Owner, job.WindowStart, job.WindowEnd, job.Cursor, ct);<br>        await store.UpsertAsync(page.Orders, ct);<br><br>        return new JobPage(page.NextCursor, page.Orders.Count);<br>    }<br>}</pre><p>Ondan tek isteğim upsert ile yazması. Bir sayfa iki kere gelebilir: yazdıktan sonra cursor kaydedilmeden çökersen ve iki pencerenin örtüştüğü yerde.</p><p>Gerisi nelerin var olması gerektiğini söylemek:</p><pre>queue.Snapshot&lt;ProductHandler&gt;(&quot;products&quot;, every: TimeSpan.FromDays(1));<br><br>queue.Windowed&lt;OrderHandler&gt;(&quot;orders&quot;,<br>    horizon: TimeSpan.FromDays(730),<br>    slice: TimeSpan.FromDays(30),<br>    every: TimeSpan.FromMinutes(15),<br>    overlap: TimeSpan.FromMinutes(5));</pre><p>slice için bir not, çünkü onu da yanlış yaptık. Bir ara iş sayısı azalsın diye 30 günden 90 güne çıkardık. En büyük hesapta tek bir dilim 43.000 kayıt, 430 sayfa, yaklaşık yirmi saatlik istek oldu. Sayfa token’larının ömrü ise yirmi dört saatti. Dilimin sonlarına doğru gelen her aksaklık neredeyse bir güne mal oluyordu. Dilim, bölünemeyen en büyük iş parçası. Küçük tut.</p><h3>Denemek istersen</h3><p>Repo’da hazır bir demo var. Postgres ile birlikte, dört sahte mağaza hesabını senkronize eden küçük bir uygulama kalkıyor. Sahte mağaza yavaş cevap veriyor, arada 429 ya da 503 dönüyor ve bir hesabın bir sayfası bilerek bozuk.</p><pre>git clone https://github.com/ferhatblnk/synclane<br>cd synclane<br>docker compose up --build</pre><p>Sonra tarayıcıda <a href="http://localhost:8080/">http://localhost:8080</a> adresini aç. Şeridi paylaşan iki hesap sırayla çalışıyor, diğerleri yanlarında koşuyor. Siparişler en yeni aydan geriye doğru geliyor. Patlayan işler cursor’larından devam ediyor. Bir iş failed, deferred ve abandoned’dan geçiyor. Requeue’ya basınca cursor 50’den tamamlanıyor. Her şey çalışırken docker compose restart demo dersen çalışan işler pending’e dönüyor ve restart’tan sonra kaldıkları yerden sürüyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JogvnBpeFjhiB8KRtTZ2iA.png" /></figure><p>Sayfaya da gerek yok aslında. Tablo orada duruyor:</p><pre>docker compose exec postgres psql -U postgres -d synclane \<br>  -c &quot;select id, owner, type, status, cursor, attempt_count, error from synclane.jobs&quot;</pre><h3><strong>Şu an nerede</strong></h3><p>Bu yazıyı yazdığımda sürüm 0.1&#39;di. Şimdi 0.6. Yazıdaki tasarım değişmedi; sonradan gelenler onun üstüne kuruldu:</p><ul><li>NuGet’te: dotnet add package SyncLane.</li><li>Worker’lar yeni işi LISTEN/NOTIFY ile duyuyor, PgBouncer arkasında da. Duyamadıklarında belli aralıklarla soruyorlar.</li><li>Rate budget’lar: bir hesaba giden istekler, bütün worker’ların paylaştığı, tanımlı bir hızla gidiyor. Bir 429 o hesabı her yerde yavaşlatıyor.</li><li>Recipe’ler: JSON’u sayfa sayfa listeleyen bir API için handler yerine küçük bir JSON dosyası yeterli. Bunu bir curl’den yapay zekâ asistanı da yazabiliyor.</li><li>HTTP endpoint’leriyle bir monitor API’si, health check, öncelikler, sync-now ve sıralı kuyruklar.</li><li>Bir iş devralındıktan sonra her yazma yalnızca worker’ın adına değil, lease’in kendisine bağlı. Buna yol açan yorumu için Tim Urista’ya teşekkürler.</li></ul><p>Bazı şeyler hâlâ geçerli. Tasarım uzun zamandır production’da çalışıyor, ama bu kod henüz çalışmadı; önce bozulmasında sakınca olmayan bir şeyde dene. Yalnızca PostgreSQL ile çalışıyor ve bir işin hâlâ özel argümanları yok. Değişen her şey <a href="https://github.com/ferhatblnk/synclane/blob/main/CHANGELOG.md">changelog</a>’da.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a9afddc53ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your errors are sitting in Loki. Who’s looking at them?]]></title>
            <link>https://medium.com/@ferhatblnk/your-errors-are-sitting-in-loki-whos-looking-at-them-cf200c590bcc?source=rss-d2887a0d5055------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf200c590bcc</guid>
            <category><![CDATA[atlassian]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[jira]]></category>
            <category><![CDATA[exception]]></category>
            <dc:creator><![CDATA[Ferhat Talha BULANIK]]></dc:creator>
            <pubDate>Tue, 06 Oct 2026 10:03:23 GMT</pubDate>
            <atom:updated>2026-10-06T11:38:11.455Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hHWI5GKZOYQuqIYie-b0A.png" /></figure><p>I wrote a small service that groups the errors in Loki and opens one Jira issue for each of them. This is how it works and why I built it the way I did.</p><p><em>Türkçesi: </em><a href="https://medium.com/@ferhatblnk/hatalar-lokide-duruyor-peki-onlara-kim-bak%C4%B1yor-33532ab581b0"><em>Hatalar Loki’de duruyor, peki onlara kim bakıyor?</em></a></p><p>If your team runs Loki and Grafana, finding an error is easy. You write a query and there it is. What’s missing is someone to write that query.</p><p>In most teams it goes roughly like this. Somebody opens a dashboard, because of a complaint or by accident, and spots an exception they haven’t seen before. They ask whether it’s a known one, and nobody is sure. Then they either write a Jira ticket by hand or say “we’ll look at it later” and close the tab. The second one happens more often.</p><p>Tools like Sentry solve this, and they do it well. But it’s another system: you host it yourself or you pay as your volume grows, and every service gets an SDK. Meanwhile the errors are already being logged and they’re already in Loki. The only missing piece is someone who checks those logs regularly and says “this one is new, I’ll open a ticket.”</p><p>So I wrote a small service that does that part. It’s called LogTriage, it’s <a href="https://github.com/ferhatblnk/logtriage">open source on GitHub</a>, and it’s MIT licensed.</p><h3>What it does</h3><p>It reads the error lines in Loki, puts repeats of the same error into one group, and opens a single Jira issue per group. If the same error shows up a thousand times, there’s still one issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tWakomadZgHeU48oqyMjiw.png" /></figure><p>It runs every few minutes. It pulls the last hour of error lines from Loki, decides which of them are the same error, and picks the ones worth a ticket. Then it asks Jira whether an issue already exists for that error. If it does, nothing happens. If it doesn’t, one gets created.</p><p>The issue has the service name, how many times the error occurred, when it was first and last seen, the message, the stack trace, and a ready-made query to find it in Loki again. Whoever picks it up doesn’t have to start by asking the same questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OFr00j3vccmyvdtsziJ1DA.png" /></figure><p><em>An issue from the demo. The password and the token reach Jira masked.</em></p><h3>What counts as “the same error”</h3><p>This was the part I spent the most time thinking about. How do you decide that two log lines are the same error?</p><p>The obvious answer is to compare messages. But messages usually carry an id: “Order 41 has no shipping address” and “Order 42 has no shipping address” are the same error with different text. Stack traces aren’t reliable either, because line numbers move with every deploy.</p><p>In LogTriage an error’s identity is made of five things: service, exception type, HTTP method, route and status code. The message and the stack trace are left out on purpose. That way GET /orders/41 and GET /orders/42 land in the same group, and a new deploy doesn&#39;t make an old error look new.</p><p>There’s a cost, of course. Two different bugs that throw the same exception type on the same endpoint show up as one issue. I chose to be wrong in that direction, because the opposite fills the board with duplicates and after a while people stop looking at it.</p><h3>No database</h3><p>You need to remember which errors already have an issue. The first instinct is to add a table. I didn’t.</p><p>Every issue gets a label that carries the error’s fingerprint, something like logtriage-6d30b0cbffa75174. Before opening a new issue I search Jira for that label. If it&#39;s there, the issue already exists.</p><p>So Jira itself is the record. Nothing is lost when the service restarts, there’s nothing to back up, and there’s one less thing to install. It has a nice side effect too: if you closed an issue and want a new one the next time that error comes back, you just remove the label from the old one.</p><h3>Watch first, then switch it on</h3><p>The biggest fear when you run a tool like this for the first time is fifty tickets landing on your team’s board at once. So LogTriage starts in dry-run mode by default. It doesn’t touch Jira at all, it only logs “I would open this.” You look at the list, adjust the query and the thresholds, and turn it on when you’re comfortable.</p><p>There are brakes after that too. By default only 5xx errors get an issue, so things like 404s are skipped. A single run opens at most five issues, starting with the most frequent error. If a bad deploy breaks fifty endpoints, the board fills up gradually and the ones that hurt most arrive first.</p><h3>Be careful about what goes to Jira</h3><p>Logs can be full of sensitive things, and Jira is usually visible to more people than your logs are. So I made two decisions.</p><p>First, the query string and body of the request aren’t added to the issue by default. You turn that on if you want it.</p><p>Second, when you do turn it on, the data is cleaned first. Fields with words like password, token or secret in their name get *** as their value. If the request contains something that looks like a card number or an IBAN, it isn&#39;t written to the issue at all, and a note says it was withheld.</p><p>I should also say it isn’t perfect. It can’t recognise every secret, and it won’t catch a password that somebody wrote into an exception message. That’s why it’s off by default.</p><h3>If you want to try it</h3><p>There’s a ready-made demo in the repo. It starts a sample API that fails on purpose, Loki, LogTriage, and a small fake service standing in for Jira so you don’t need an account:</p><pre>git clone https://github.com/ferhatblnk/logtriage<br>cd logtriage<br>docker compose up --build</pre><p>Then open http://localhost:8081 in your browser. Within a minute or two, three issues show up, one for each broken endpoint. It stays at three no matter how long you wait. A fourth endpoint returns 404, so it doesn&#39;t get one.</p><h3>Connecting your own service</h3><p>All LogTriage needs from your service is a JSON log line that says what happened when a request failed. I’ve spread it over several lines here so it’s readable. In the log it’s a single line:</p><pre>{<br>  &quot;exception.type&quot;: &quot;System.InvalidOperationException&quot;,<br>  &quot;exception.message&quot;: &quot;Order 41 has no shipping address.&quot;,<br>  &quot;http.request.method&quot;: &quot;GET&quot;,<br>  &quot;http.route&quot;: &quot;/orders/{id}&quot;,<br>  &quot;http.response.status_code&quot;: 500<br>}</pre><p>The field names follow the OpenTelemetry conventions, and only exception.type is required. For ASP.NET Core there&#39;s a sixty-line middleware in the repo that you can copy. If your logs already have a different shape, you change the field names in the settings and leave your logs alone. The language your service is written in doesn&#39;t matter either, as long as it logs the same fields.</p><p>LogTriage itself is written in .NET 10 and has no third-party dependencies at runtime.</p><h3>What it can’t do yet</h3><p>This is version 0.1, so it’s early. What you should know:</p><ul><li>It only works with Jira Cloud. There’s no Data Center support.</li><li>It was written with HTTP services in mind. Background jobs have no route, so grouping is coarse there.</li><li>If the error behind a closed issue comes back, the issue isn’t reopened automatically.</li></ul><p>When you try it on your own logs, I’d run it in dry-run mode first and look at what it would open.</p><p>The code is here: <a href="https://github.com/ferhatblnk/logtriage">github.com/ferhatblnk/logtriage</a>. If you try it and get stuck, or your logs look different and it didn’t work, open an issue. If you’d like to add something that’s missing, pull requests are welcome too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf200c590bcc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hatalar Loki’de duruyor, peki onlara kim bakıyor?]]></title>
            <link>https://medium.com/@ferhatblnk/hatalar-lokide-duruyor-peki-onlara-kim-bak%C4%B1yor-33532ab581b0?source=rss-d2887a0d5055------2</link>
            <guid isPermaLink="false">https://medium.com/p/33532ab581b0</guid>
            <category><![CDATA[loki]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[atlassian]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[jira]]></category>
            <dc:creator><![CDATA[Ferhat Talha BULANIK]]></dc:creator>
            <pubDate>Tue, 06 Oct 2026 09:39:23 GMT</pubDate>
            <atom:updated>2026-10-06T11:38:28.258Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5hHWI5GKZOYQuqIYie-b0A.png" /></figure><p>Loki’deki hataları gruplayıp her biri için tek bir Jira maddesi açan küçük bir servis yazdım. Nasıl çalıştığını ve neden böyle kurduğumu anlatıyorum.</p><p><em>English version: </em><a href="https://medium.com/@ferhatblnk/your-errors-are-sitting-in-loki-whos-looking-at-them-cf200c590bcc"><em>Your errors are sitting in Loki. Who’s looking at them?</em></a></p><p>Loki ve Grafana kurulu bir ekipte hatayı bulmak zor değil. Sorguyu yazarsın, exception karşına çıkar. Zor olan başka bir şey: o sorguyu yazacak birinin olması.</p><p>Çoğu ekipte döngü aşağı yukarı aynı işliyor. Biri bir şikâyet üzerine ya da tesadüfen dashboard’a bakıyor ve yeni bir exception görüyor. “Bu biliniyor mu?” diye soruyor, kimse emin değil. Sonra ya Jira’ya elle bir madde yazıyor ya da “sonra bakarız” deyip sekmeyi kapatıyor. İkincisi daha sık oluyor.</p><p>Sentry gibi araçlar bu işi çözüyor, hakkını vermek lazım. Ama ayrı bir sistem demek: ya kendin barındırırsın ya da hacim büyüdükçe ücret ödersin, üstüne her servise bir SDK eklersin. Hâlbuki hatalar zaten loglanıyor ve zaten Loki’de duruyor. Eksik olan tek şey, birinin o loglara düzenli bakıp “bu yeni bir hata, şuraya madde açayım” demesi.</p><p>Ben de bu kısmı otomatiğe bağlayan küçük bir servis yazdım. Adı LogTriage. <a href="https://github.com/ferhatblnk/logtriage">GitHub’da açık kaynak</a>, MIT lisanslı.</p><h3>Ne yapıyor</h3><p>Loki’deki hata satırlarını okuyor, aynı hatanın tekrarlarını bir grupta topluyor ve her grup için Jira’da tek bir madde açıyor. Aynı hata bin kere de gelse madde bir tane kalıyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JOVXnQvB36DR8FFHFmGyCw.png" /></figure><p>Birkaç dakikada bir çalışıyor. Son bir saatin hata satırlarını Loki’den çekiyor, hangilerinin aynı hata olduğuna karar veriyor ve madde açmaya değenleri ayırıyor. Sonra Jira’ya “bu hata için daha önce madde açılmış mı” diye soruyor. Açılmışsa dokunmuyor, açılmamışsa açıyor.</p><p>Maddenin içinde servis adı, hatanın kaç kere görüldüğü, ilk ve son görülme zamanı, mesaj, stack trace ve hatayı Loki’de tekrar bulmak için hazır bir sorgu oluyor. Maddeyi eline alan kişi aynı soruları baştan sormak zorunda kalmıyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OFr00j3vccmyvdtsziJ1DA.png" /></figure><p><em>Demodan bir madde. Şifre ve token Jira’ya </em><em>*** olarak gidiyor.</em></p><h3>“Aynı hata” ne demek</h3><p>İşin en çok düşündüren kısmı buydu. İki log satırının aynı hata olduğuna nasıl karar verirsin?</p><p>İlk akla gelen mesaja bakmak. Ama mesajların içinde genelde bir kimlik olur: “41 numaralı siparişin adresi yok” ile “42 numaralı siparişin adresi yok” aynı hatadır, mesajları farklıdır. Stack trace de güvenilir değil, her deploy’da satır numaraları kayar.</p><p>LogTriage’da bir hatanın kimliği beş şeyden oluşuyor: servis, exception tipi, HTTP metodu, route ve status kodu. Mesaj ve stack trace bilerek dışarıda. Böylece GET /orders/41 ile GET /orders/42 aynı gruba düşüyor, yeni bir deploy da eski hatayı yeni hata gibi göstermiyor.</p><p>Bunun bir bedeli var tabii. Aynı endpoint’te aynı exception tipiyle patlayan iki farklı bug tek madde olarak görünür. Ben bu tarafta yanılmayı tercih ettim, çünkü tersi panoyu kopya maddelerle dolduruyor ve insanlar bir süre sonra bakmayı bırakıyor.</p><h3>Veritabanı yok</h3><p>Hangi hata için madde açıldığını bir yerde tutmak lazım. İlk refleks bir tablo açmak olur. Ben açmadım.</p><p>Her maddeye hatanın parmak izini taşıyan bir etiket koyuyorum, logtriage-6d30b0cbffa75174 gibi. Yeni bir madde açmadan önce Jira&#39;da bu etiketi arıyorum. Varsa madde zaten açılmış demektir.</p><p>Yani kayıt defteri Jira’nın kendisi. Servis yeniden başladığında hiçbir şey kaybolmuyor, yedeklenecek bir şey yok, kurulumda fazladan bir bileşen yok. Hoş bir yan etkisi de var: kapattığın bir maddenin hatası geri gelirse yeniden madde açılsın istiyorsan eski maddeden etiketi silmen yetiyor.</p><h3>Önce izle, sonra aç</h3><p>Böyle bir aracı ilk kez çalıştırırken en büyük korku, ekibin panosuna bir anda elli madde düşmesi. O yüzden LogTriage varsayılan olarak “dry run” modunda açılıyor. Jira’ya hiç dokunmuyor, sadece “şunu açardım” diye log yazıyor. Listeye bakıyorsun, sorguyu ve eşikleri ayarlıyorsun, için rahat edince açıyorsun.</p><p>Açtıktan sonra da frenler var. Varsayılan olarak yalnızca 5xx hatalar için madde açılıyor, 404 gibi şeyler geçiliyor. Bir turda en fazla beş madde açılıyor, en sık görülen hatadan başlayarak. Kötü bir deploy elli endpoint’i birden bozarsa pano yavaş yavaş doluyor ve önce en çok can yakanlar geliyor.</p><h3>Jira’ya ne gittiğine dikkat</h3><p>Loglar hassas şeylerle dolu olabiliyor ve Jira’yı genelde logları görenlerden daha fazla kişi görüyor. Bu yüzden iki karar aldım.</p><p>Birincisi, isteğin query string’i ve gövdesi varsayılan olarak maddeye hiç eklenmiyor. İstersen açıyorsun.</p><p>İkincisi, açtığında önce bir temizlikten geçiyor. Adında password, token, secret gibi kelimeler geçen alanların değeri *** oluyor. İstekte kart numarasına ya da IBAN&#39;a benzeyen bir şey varsa o istek maddeye hiç yazılmıyor, yerine &quot;gizlendi&quot; notu düşüyor.</p><p>Kusursuz olmadığını da söyleyeyim. Her sırrı tanıyamaz, exception mesajının içine yazılmış bir şifreyi de yakalayamaz. Varsayılanın kapalı olmasının sebebi bu.</p><h3>Denemek istersen</h3><p>Repo’da hazır bir demo var. Bilerek hata veren örnek bir API, Loki, LogTriage ve hesap açmana gerek kalmasın diye Jira’nın yerine geçen küçük bir sahte servis birlikte kalkıyor:</p><pre>git clone https://github.com/ferhatblnk/logtriage<br>cd logtriage<br>docker compose up --build</pre><p>Sonra tarayıcıda http://localhost:8081 adresini aç. Bir iki dakika içinde üç madde düşüyor, her bozuk endpoint için bir tane. Ne kadar beklersen bekle üç kalıyor. Dördüncü endpoint 404 döndüğü için ona madde açılmıyor.</p><h3>Kendi servisine bağlamak</h3><p>LogTriage’ın servisinden istediği tek şey, bir istek patladığında ne olduğunu söyleyen bir JSON log satırı. Okunsun diye alt alta yazdım, logda tek satır:</p><pre>{<br>  &quot;exception.type&quot;: &quot;System.InvalidOperationException&quot;,<br>  &quot;exception.message&quot;: &quot;Order 41 has no shipping address.&quot;,<br>  &quot;http.request.method&quot;: &quot;GET&quot;,<br>  &quot;http.route&quot;: &quot;/orders/{id}&quot;,<br>  &quot;http.response.status_code&quot;: 500<br>}</pre><p>Alan adları OpenTelemetry’nin adlandırmasını izliyor, zorunlu olan yalnızca exception.type. ASP.NET Core için repo&#39;da kopyalayıp kullanabileceğin altmış satırlık bir middleware var. Logların zaten başka bir biçimdeyse alan adlarını ayarlardan değiştiriyorsun, loglarına dokunman gerekmiyor. Servisin hangi dille yazıldığı da önemli değil, aynı alanları loglaması yeterli.</p><p>LogTriage’ın kendisi .NET 10 ile yazıldı ve çalışırken üçüncü parti hiçbir pakete bağımlı değil.</p><h3>Henüz yapamadıkları</h3><p>Sürüm 0.1, yani erken. Bilmen gerekenler:</p><ul><li>Yalnızca Jira Cloud ile çalışıyor, Data Center desteği yok.</li><li>HTTP servisleri düşünülerek yazıldı. Arka plan işlerinde route olmadığı için gruplama kaba kalıyor.</li><li>Kapanmış bir maddenin hatası geri gelirse madde kendiliğinden yeniden açılmıyor.</li></ul><p>Kendi loglarında denerken önce dry run ile çalıştırıp ne açacağına bakmanı öneririm.</p><p>Kod burada: <a href="https://github.com/ferhatblnk/logtriage">github.com/ferhatblnk/logtriage</a>. Deneyip takıldığın bir yer olursa ya da “bizim loglar şöyle, çalışmadı” dersen issue aç. Eksik gördüğün bir şeyi eklemek istersen PR’a da açığım.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33532ab581b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Enhancing Angular Reactive Forms with Custom Validation Extensions]]></title>
            <link>https://medium.com/@ferhatblnk/enhancing-angular-reactive-forms-with-custom-validation-extensions-a4efa3109f6b?source=rss-d2887a0d5055------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4efa3109f6b</guid>
            <dc:creator><![CDATA[Ferhat Talha BULANIK]]></dc:creator>
            <pubDate>Wed, 04 Jun 2025 12:25:24 GMT</pubDate>
            <atom:updated>2025-06-04T12:25:24.425Z</atom:updated>
            <content:encoded><![CDATA[<h3>✅ A Cleaner Way to Trigger Full Form Validation with Optional Notifications in Angular</h3><p>When building complex forms in Angular — especially with deeply nested FormGroups and FormArrays—manually triggering validation across all controls can get repetitive and messy. This article introduces a clean and reusable way to <strong>extend Angular’s </strong><strong>FormGroup and </strong><strong>FormArray</strong> prototypes to perform full-form validation <strong>with optional notifications</strong> using NG-ZORRO&#39;s NzNotificationService.</p><p>We’ll also see how to create <strong>custom </strong><strong>FormControl types</strong> with metadata (tag) to support more meaningful and user-friendly messages.</p><h3>🌱 Why Extend Angular Forms?</h3><p>Angular provides built-in methods like markAsDirty(), updateValueAndValidity(), and markAllAsTouched(), but applying them deeply across large forms becomes repetitive. Our goal:</p><ul><li>Recursively validate all controls</li><li>Optionally show notifications if any field is invalid</li><li>Use metadata (tag) for specific and clear warnings</li><li>Avoid clutter in components by extending the form prototypes</li></ul><h3>Step 1: Create a Custom FormControl with Metadata</h3><pre>// form-control-ext.ts<br>import { FormControl } from &#39;@angular/forms&#39;;<br><br>export class ExampleFormControl extends FormControl {<br>  tag?: string; // Optional field label for notifications<br>}</pre><h3>🧠 Step 2: Add Prototype Extensions to FormGroup and FormArray</h3><pre>// form-validation-ext.ts<br>import {<br>  FormGroup,<br>  FormArray,<br>  FormControl,<br>  AbstractControl,<br>} from &#39;@angular/forms&#39;;<br>import { NzNotificationService } from &#39;ng-zorro-antd/notification&#39;;<br>import { ExampleFormControl } from &#39;./form-control-ext&#39;;<br><br>// Extend Angular types<br>declare module &#39;@angular/forms&#39; {<br>  interface FormGroup {<br>    ExampleFormValidation(<br>      notificationService?: NzNotificationService<br>    ): boolean;<br>  }<br><br>  interface FormArray {<br>    ExampleFormValidation(<br>      notificationService?: NzNotificationService<br>    ): boolean;<br>  }<br>}</pre><h3>🔧 Step 3: Implement Recursive Validation Logic</h3><pre>let globalNotificationService: NzNotificationService | null = null;<br><br>export function setGlobalNotificationService(service: NzNotificationService) {<br>  globalNotificationService = service;<br>}<br><br>function validateControl(<br>  control: AbstractControl,<br>  notify?: (msg: string) =&gt; void<br>): void {<br>  control.markAsDirty();<br>  control.updateValueAndValidity();<br><br>  if (<br>    control instanceof ExampleFormControl &amp;&amp;<br>    control.invalid &amp;&amp;<br>    (control.dirty || control.touched) &amp;&amp;<br>    control.tag?.trim() &amp;&amp;<br>    notify<br>  ) {<br>    notify(`${control.tag} field is required or invalid.`);<br>  }<br>}<br><br>function visitAllControls(<br>  control: AbstractControl,<br>  notify?: (msg: string) =&gt; void<br>): void {<br>  if (control instanceof FormControl) validateControl(control, notify);<br>  else if (control instanceof FormGroup || control instanceof FormArray) {<br>    Object.values(control.controls).forEach((child) =&gt;<br>      visitAllControls(child, notify)<br>    );<br>  }<br>}<br><br>function getAllControls(form: FormGroup | FormArray): AbstractControl[] {<br>  const controls: AbstractControl[] = [];<br><br>  Object.values(form.controls).forEach((control) =&gt; {<br>    if (control instanceof FormControl) controls.push(control);<br>    else if (control instanceof FormGroup || control instanceof FormArray)<br>      controls.push(...getAllControls(control));<br>  });<br><br>  return controls;<br>}<br><br>function validateFormWithNotification(<br>  form: FormGroup | FormArray,<br>  notificationService?: NzNotificationService<br>): boolean {<br>  const service = notificationService || globalNotificationService;<br>  const notify = service<br>    ? (msg: string) =&gt; service.warning(&#39;Warning&#39;, msg)<br>    : undefined;<br><br>  visitAllControls(form, notify);<br><br>  if (!form.valid &amp;&amp; service) {<br>    const hasTaggedInvalid = getAllControls(form).some(<br>      (ctrl) =&gt;<br>        ctrl instanceof ExampleFormControl &amp;&amp;<br>        ctrl.invalid &amp;&amp;<br>        !!ctrl.tag?.trim()<br>    );<br><br>    if (!hasTaggedInvalid) notify?.(&#39;Please fill in the required fields.&#39;);<br>  }<br><br>  return form.valid;<br>}</pre><h3>🧩 Step 4: Attach Methods to FormGroup and FormArray Prototypes</h3><pre>(FormGroup.prototype as any).ExampleFormValidation = function (<br>  notificationService?: NzNotificationService<br>): boolean {<br>  return validateFormWithNotification(this, notificationService);<br>};<br><br>(FormArray.prototype as any).ExampleFormValidation = function (<br>  notificationService?: NzNotificationService<br>): boolean {<br>  return validateFormWithNotification(this, notificationService);<br>};</pre><h3>🧪 Usage Example</h3><pre>const form = new FormGroup({<br>  name: new ExampleFormControl(&#39;&#39;, { tag: &#39;Name&#39;, validators: [...] }),<br>  address: new FormGroup({<br>    city: new ExampleFormControl(&#39;&#39;, { tag: &#39;City&#39;, validators: [...] }),<br>  }),<br>});<br><br>form.ExampleFormValidation(notificationService);</pre><h3>🎯 Final Thoughts</h3><p>Extending Angular’s form types can <strong>simplify form validation</strong>, improve <strong>user experience</strong>, and maintain <strong>cleaner components</strong>. By abstracting validation logic and leveraging metadata like tag, your forms become more scalable and maintainable.</p><p>Feel free to adapt this approach to your design system or notification library — whether you’re using NG-ZORRO, Angular Material, or a custom service.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4efa3109f6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NET 9 Some Useful New Features]]></title>
            <link>https://medium.com/@ferhatblnk/net-9-some-useful-new-features-40d325369cab?source=rss-d2887a0d5055------2</link>
            <guid isPermaLink="false">https://medium.com/p/40d325369cab</guid>
            <dc:creator><![CDATA[Ferhat Talha BULANIK]]></dc:creator>
            <pubDate>Sat, 12 Oct 2024 09:39:59 GMT</pubDate>
            <atom:updated>2024-10-12T09:40:17.658Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MuxjdrCu0WLrXTZ9UtZu9w.jpeg" /></figure><p>Hello everyone, in this article, I will discuss some of the new features introduced with .NET 9. These features will provide us with speed and many advantages while coding in our current project. Let’s go over these innovations together one by one.</p><ol><li><strong>CountBy() Metodu</strong>​</li><li><strong>AggregateBy() Metodu</strong>​</li><li><strong>Index() Metodu</strong>​</li><li><strong>List Patterns (Liste Desenleri)</strong>​</li><li><strong>Threading.Lock</strong></li></ol><p><strong>.CountBy()<br></strong>Groups elements in a collection based on a specified key value and returns the count of elements for each group. This method allows you to quickly obtain the count of elements per group.</p><p><strong>Importance:</strong></p><ul><li>It is highly useful for data analysis and reporting because it allows you to quickly summarize your data based on specific criteria.</li><li>By performing grouping and counting in a single step, it makes your code more readable and efficient.</li></ul><pre><br> var fruits = new List&lt;string&gt; { &quot;apple&quot;, &quot;banana&quot;, &quot;apple&quot;, &quot;orange&quot;, &quot;banana&quot;, &quot;apple&quot;};<br><br> var fruitCounts = fruits.CountBy(fruit =&gt; fruit);<br><br> foreach (var (fruit, count) in fruitCounts)<br> {<br>     Console.WriteLine($&quot;fruit: {fruit}, Count: {count}&quot;);<br> }<br></pre><p><strong>Output :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/1*4ewli_duqsWU9eNhHK_AcA.png" /></figure><p><strong>.AggregateBy()</strong></p><p>groups a collection based on a specified key and allows you to perform operations like sum, average, etc., for each group. This method is used to apply an aggregate operation over each group in the collection.</p><p><strong>Importance:</strong></p><ul><li>It simplifies the code and enhances performance by combining grouping and aggregation operations.</li></ul><pre> var scores = new List&lt;(string PlayerId, int Score)&gt;<br>        {<br>            (&quot;1&quot;, 50), <br>            (&quot;2&quot;, 30), <br>            (&quot;1&quot;, 20), <br>            (&quot;2&quot;, 40)<br>        };<br><br>        var aggregatedScores = scores.AggregateBy(<br>            score =&gt; score.PlayerId, // Selector<br>            200, // Seed Data<br>            (total, current) =&gt; total + current.Score // Function<br>        );<br><br>        foreach (var score in aggregatedScores)<br>        {<br>            Console.WriteLine($&quot;Oyuncu {score.Key} toplam skoru: {score.Value}&quot;);<br>        }</pre><p><strong>Output :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*cQ7aGu1AL-vbQCg5Ly44xg.png" /></figure><p><strong>.Index()</strong></p><p>The <strong>.Index()</strong> method searches for elements in a collection based on a specified condition and returns the index (position) of the found item. If the element is not found in the collection, it returns a default value (-1).</p><p><strong>Importance:</strong></p><ul><li>It allows you to quickly find the position of elements within collections.</li><li>It provides an efficient way to locate a specific item, especially in large datasets.</li></ul><pre>  var fruits = new List&lt;string&gt; { &quot;Apple&quot;, &quot;Banana&quot;, &quot;Cherry&quot;, &quot;Date&quot;, &quot;Elderberry&quot; };<br>  foreach (var (index, fruit) in fruits.Index())<br>  {<br>      Console.WriteLine($&quot;Index: {index}, Fruit: {fruit}&quot;);<br>  }</pre><p><strong>Output :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*GnWBm82wmYUPODarSSJIuQ.png" /></figure><p><strong>List Patterns</strong></p><p><strong>List Patterns</strong> is a feature added to the C# language that allows you to perform pattern matching on lists and arrays to check for specific elements. It is used to verify whether collections conform to a specific structure and to inspect the values of their elements.</p><p><strong>Importance:</strong></p><ul><li>It offers a more readable and straightforward way to check whether collections follow a certain structure.</li><li>Especially when working with data structures, the flexibility provided by pattern matching simplifies code writing.</li></ul><pre>var numbers = new List&lt;int&gt;{1,2,3,4,5};<br><br>if (numbers is [..,4,5])<br>    Console.WriteLine(&quot;List starts with 1,2,3 n continue&quot;);<br>else<br>    Console.WriteLine(&quot; The list does not conform to the expected structure&quot;);</pre><p><strong>Output :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*V9EPPO5T99jvJcVYcZ0odA.png" /></figure><p><strong>System.Threading.Lock</strong></p><p><strong>Lock Object:</strong> We create a new Lock object with private static Lock myLock = new Lock();. This provides synchronization between threads.</p><p><strong>Threads:</strong> Two threads, Thread t1 and Thread t2, are created, each calling the IncrementCounter method.</p><p><strong>Critical Section:</strong> A critical section is defined with the expression using (myLock.EnterScope()). Within this block, only one thread can access the counter variable at a time, preventing both threads from incrementing the counter simultaneously.</p><p><strong>Waiting for Threads to Finish:</strong> The calls to t1.Join(); and t2.Join(); ensure that the main thread waits for both t1 and t2 to finish.</p><pre>class Program<br>{<br>    private static readonly Lock myLock = new Lock();<br>    private static int counter = 0;<br><br>    static void Main()<br>    {<br>        Thread t1 = new Thread(IncrementCounter);<br>        Thread t2 = new Thread(IncrementCounter);<br><br>        t1.Start();<br>        t2.Start();<br><br>        t1.Join();<br>        t2.Join();<br><br>        Console.WriteLine($&quot;Result: {counter}&quot;);<br>    }<br><br>    static void IncrementCounter()<br>    {<br>        using (myLock.EnterScope())<br>        {<br>            for (int i = 0; i &lt; 10000; i++)<br>            {<br>                counter++;<br>            }<br>        }<br>    }<br>}</pre><p>I wanted to briefly touch on these new improvements. You can try these scenarios with example code blocks and apply them in appropriate places in your own projects. I hope this will be useful for you as well. Have a great day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40d325369cab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 18 / .NET 8 SignalR Usage]]></title>
            <link>https://medium.com/@ferhatblnk/angular-18-net-8-signalr-usage-6d0186906946?source=rss-d2887a0d5055------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d0186906946</guid>
            <category><![CDATA[realtime-applications]]></category>
            <category><![CDATA[signalr]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Ferhat Talha BULANIK]]></dc:creator>
            <pubDate>Tue, 09 Jul 2024 07:36:10 GMT</pubDate>
            <atom:updated>2024-07-09T07:36:10.858Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular 18 / .NET 8 SignalR Usage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjMoD0Gi1CmcyyO4JwsSMA.jpeg" /></figure><p>In this article, we will explore how to establish a SignalR connection using Angular 18 and .NET 8, step by step. First, we create our .NET 8 project and add the SignalR library to the project. Then, we start our Angular 18 project and include the SignalR client library in the Angular project. On the .NET side, we create a Hub class and define the necessary methods. On the Angular side, we create a service to initialize the SignalR connection. For example, we create a “ChatHub” class in .NET and define a method called “SendMessage.” In Angular, we set up the connection settings in the “chat.service.ts” file to call this method. Using Angular’s lifecycle methods to establish and manage the connection is crucial. With these examples, you’ll learn how to easily implement real-time data communication in your Angular 18 and .NET 8 projects using SignalR.</p><p>To set up the SignalR connection, we first need to install the necessary SignalR package in our .NET 8 project. We do this by adding the Microsoft.AspNetCore.SignalR package via NuGet. Then, we create our SignalR hub class:</p><pre>public class ChatHub : Hub<br>{<br>    public async Task SendMessage(string user, string message)<br>    {<br>        await Clients.All.SendAsync(&quot;ReceiveMessage&quot;, user, message);<br>    }</pre><p>This class contains the basic functions of our SignalR hub. The SendMessage method sends the received message to all connected clients. Next, we update our Program.cs file to create an endpoint that uses this hub:</p><pre>using Microsoft.AspNetCore.Builder;<br>using Microsoft.Extensions.DependencyInjection;<br>using Microsoft.Extensions.Hosting;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>// Add services to the container.<br>builder.Services.AddControllersWithViews();<br>builder.Services.AddSignalR(); // Add SignalR Service<br><br>var app = builder.Build();<br><br>// Configure the HTTP request pipeline.<br>if (app.Environment.IsDevelopment())<br>{<br>    app.UseDeveloperExceptionPage();<br>}<br>else<br>{<br>    app.UseExceptionHandler(&quot;/Home/Error&quot;);<br>    app.UseHsts();<br>}<br><br>app.UseHttpsRedirection();<br>app.UseStaticFiles();<br><br>app.UseRouting();<br><br>app.UseAuthorization();<br><br>app.MapControllerRoute(<br>    name: &quot;default&quot;,<br>    pattern: &quot;{controller=Home}/{action=Index}/{id?}&quot;);<br>app.MapHub&lt;ChatHub&gt;(&quot;/chathub&quot;); // Add ChatHub<br><br>app.Run();</pre><p>After completing the configuration on the .NET side, we move to our Angular 18 project. The first step is to add the @microsoft/signalr package to our Angular project</p><pre>npm install @microsoft/signalr</pre><p>Next, we create a service to manage the SignalR connection. In the chat.service.ts file, we define the functions to establish the connection and send messages:</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import * as signalR from &#39;@microsoft/signalr&#39;;</pre><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class ChatService {<br>  private hubConnection: signalR.HubConnection;<br>  constructor() {<br>    this.hubConnection = new signalR.HubConnectionBuilder()<br>      .withUrl(&#39;/chathub&#39;)<br>      .build();<br>    this.hubConnection.on(&#39;ReceiveMessage&#39;, (user, message) =&gt; {<br>      console.log(`User: ${user}, Message: ${message}`);<br>    });<br>    this.hubConnection.start()<br>      .catch(err =&gt; console.error(err));<br>  }<br>  sendMessage(user: string, message: string): void {<br>    this.hubConnection.invoke(&#39;SendMessage&#39;, user, message)<br>      .catch(err =&gt; console.error(err));<br>  }<br>}</pre><p>This service establishes the SignalR connection and listens for incoming messages. It also provides the sendMessage method to send messages. Now, we can use this service in our Angular component to send messages from the user interface and display incoming messages:</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { ChatService } from &#39;./chat.service&#39;;</pre><pre>@Component({<br>  selector: &#39;app-chat&#39;,<br>  template: `<br>    &lt;div&gt;<br>      &lt;input [(ngModel)]=&quot;user&quot; placeholder=&quot;User&quot; /&gt;<br>      &lt;input [(ngModel)]=&quot;message&quot; placeholder=&quot;Message&quot; /&gt;<br>      &lt;button (click)=&quot;sendMessage()&quot;&gt;Send&lt;/button&gt;<br>    &lt;/div&gt;<br>    &lt;div *ngFor=&quot;let msg of messages&quot;&gt;<br>      {{msg}}<br>    &lt;/div&gt;<br>  `,<br>})<br>export class ChatComponent {<br>  user = &#39;&#39;;<br>  message = &#39;&#39;;<br>  messages: string[] = [];<br>  constructor(private chatService: ChatService) {}<br>  sendMessage(): void {<br>    this.chatService.sendMessage(this.user, this.message);<br>    this.messages.push(`You: ${this.message}`);<br>    this.message = &#39;&#39;;<br>  }<br>}</pre><p>With this example, we can send messages in our Angular component and list incoming messages. These steps make it easy to implement real-time communication in Angular 18 and .NET 8 projects using SignalR.</p><h3>Advantages</h3><ol><li><strong>Real-Time Communication</strong>: SignalR provides low-latency real-time communication between the client and server. This is crucial for applications that require live updates, such as chat applications, games, and live data feeds.</li><li><strong>Easy Integration</strong>: It can be easily integrated with both .NET and Angular. SignalR provides a native solution on the .NET platform, while also offering a powerful SignalR client library for Angular.</li><li><strong>Supported Protocols</strong>: SignalR supports various transport protocols such as WebSockets, Server-Sent Events (SSE), and Long Polling. This allows the most suitable protocol to be automatically selected based on the capabilities of the environment where the application is running.</li><li><strong>Scalability</strong>: SignalR is supported by scaling options like Redis, Azure Service Bus, and SQL Server. This makes it easier for the application to handle increasing loads.</li></ol><h3>Disadvantages</h3><ol><li><strong>Increase in Request Count</strong>: Real-time communication can significantly increase the number of requests to the server. This can lead to rapid exhaustion of server resources, especially in applications with a large user base. More resources and more complex infrastructure solutions may be needed to handle high traffic.</li><li><strong>Server Load</strong>: Persistent connections place additional load on the server. This is particularly evident when using protocols like WebSockets that require constant connections. Additional hardware or optimization may be necessary for the server to handle this load.</li><li><strong>Security</strong>: Real-time data communication can increase security risks. Additional security measures must be taken to ensure the secure transmission of user data and to prevent unauthorized access.</li><li><strong>Browser Compatibility</strong>: Not all features of SignalR may be supported by every browser. Older browsers or some mobile browsers may not support modern protocols like WebSockets, which can lead to compatibility issues.</li><li><strong>Development and Maintenance Costs</strong>: Developing and maintaining real-time applications is more complex compared to standard HTTP-based applications. This can require more time and cost during both the development and maintenance phases.</li></ol><h3>Summary</h3><p>SignalR offers a powerful and flexible solution for applications that require real-time communication. However, considering disadvantages such as the increase in request count and server load, proper configuration and scaling strategies should be implemented. This way, you can make the most of SignalR’s advantages while minimizing the impact of its disadvantages.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d0186906946" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>