<?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 Kemal Aydın on Medium]]></title>
        <description><![CDATA[Stories by Kemal Aydın on Medium]]></description>
        <link>https://medium.com/@aydinkml?source=rss-90d9cb5e14f9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*G4x2X_6V2d4FgZtKg6JKaw.jpeg</url>
            <title>Stories by Kemal Aydın on Medium</title>
            <link>https://medium.com/@aydinkml?source=rss-90d9cb5e14f9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 11:17:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aydinkml/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[One File, Multiple Identities: Polyglot Files, File Format Ambiguity & Security Risks]]></title>
            <link>https://levelup.gitconnected.com/one-file-multiple-identities-polyglot-files-file-format-ambiguity-security-risks-5ebfb1eedb26?source=rss-90d9cb5e14f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ebfb1eedb26</guid>
            <category><![CDATA[application-security]]></category>
            <category><![CDATA[secure-file-upload]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[filesystem]]></category>
            <category><![CDATA[file-format-analysis]]></category>
            <dc:creator><![CDATA[Kemal Aydın]]></dc:creator>
            <pubDate>Sun, 29 Nov 2026 21:46:11 GMT</pubDate>
            <atom:updated>2026-11-29T21:46:11.707Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAiyV8jP4EZ-qIdpSVUHjA.png" /></figure><h3>Can a File Belong to More Than One Format?</h3><p>We work with dozens of file formats every day: JPEG images, PDF documents, ZIP archives, and JSON files. We usually assume that a file extension tells us what kind of content a file contains.</p><p>But what if a single file could satisfy the structural rules of multiple file formats?</p><p>Could a file recognized as a JPEG by one application be interpreted differently by another?</p><p>The answer is yes.</p><p>This behavior is associated with a concept known as <strong>Polyglot Files</strong>. In this article, we’ll explore how file formats are identified, why different parsers may interpret the same file differently, and why this matters for software security.</p><h3>How Do Computers Identify File Formats?</h3><p>Looking at a file extension alone is not enough to reliably determine its actual format.</p><p>Consider these examples:</p><ul><li>photo.jpg</li><li>document.pdf</li><li>archive.zip</li><li>data.json</li></ul><p>File extensions help operating systems and applications decide how to handle files. However, an extension does not guarantee that the underlying content matches the claimed format.</p><p>There are several mechanisms used to identify file formats.</p><h4>File Extension</h4><p>A file extension is the suffix at the end of a filename, such as .jpg, .pdf, or .zip.</p><p>It can be changed easily. Renaming a file to document.pdf does not make it a valid PDF document.</p><h4>MIME Type</h4><p>MIME types provide a standardized way to describe the media type of content.</p><p>Examples;</p><pre><strong>+-----------------------------+<br>| Format   | MIME Type        |<br>+-----------------------------+</strong><br>| JPEG     | image/jpeg       |<br>| PNG      | image/png        | <br>| PDF      | application/pdf  |<br>| ZIP      | application/zip  |<br>| JSON     | application/json |<br>+-----------------------------+</pre><p>MIME types are commonly used in HTTP communication through the Content-Type header.</p><p>However, MIME information supplied by a client cannot always be trusted because it can be manipulated.</p><h4>Magic Bytes (File Signatures)</h4><p>Many file formats have characteristic byte sequences, often located near the beginning of a file. These are known as magic bytes or file signatures.</p><p>Examples;</p><pre><strong>+------------------------------+<br>| Format   | Signature         |<br>+------------------------------+</strong><br>| JPEG     | FF D8 FF          |<br>| PNG      | 89 50 4E 47       | <br>| PDF      | 25 50 44 46 (%PDF)|<br>| ZIP      | 50 4B 03 04       | <br>+------------------------------+</pre><p>These signatures provide useful clues about a file’s format.</p><p>However, finding the expected magic bytes does not prove that a file is valid or safe.</p><h3>What Is a Parser and Why Does It Matter?</h3><p>A parser is a software component that reads structured data and interprets it according to the rules of a particular format.</p><p>For example;</p><ul><li>A PDF Reader interprets PDF documents.</li><li>An Image Decoder processes JPEG or PNG data.</li><li>A ZIP Reader interprets archive structures.</li><li>A Browser processes HTML and other web content.</li></ul><p>Different parsers may apply different rules when interpreting the same sequence of bytes.</p><p>This happens because file formats have their own structures, headers, metadata fields, termination rules, and data interpretation mechanisms.</p><p>These differences are fundamental to understanding polyglot files.</p><h3>What Is a Polyglot File?</h3><p>A Polyglot File is a file constructed to conform to the structural rules of more than one file format, allowing different applications to interpret it in different ways.</p><p>The word “polyglot” normally describes a person who speaks multiple languages. In computing, it describes a file that can effectively speak multiple format languages.</p><p>Conceptually, such a file might look like this:</p><pre>+------------------------------+<br>| Format A Header              |<br>+------------------------------+<br>| Shared / Compatible Content  |<br>+------------------------------+<br>| Format A Data                |<br>+------------------------------+<br>| Format B Structure / Data    |<br>+------------------------------+</pre><p>The important idea is that different parts of the file may satisfy the structural requirements of different formats.</p><p>One application may interpret the file according to the rules of the first format, while another may rely on a different structure.</p><p>As a result, the same file can behave differently across applications.</p><p><strong>Important:</strong> Simply appending data from another format to a file does not automatically create a valid polyglot. The resulting file must satisfy the structural requirements of both formats.</p><h3>How Do Polyglot Files Occur?</h3><p>Several technical characteristics can make polyglot files possible.</p><p><strong>Format Flexibility:</strong> Some file formats allow additional metadata, comments, or data in certain sections.</p><p><strong>Trailing Data:</strong> Some parsers may stop processing after reading the expected content and ignore the remaining bytes.</p><p><strong>Parser Differences:</strong> Different applications may implement the same format specification with varying levels of strictness.</p><p><strong>Embedded Content:</strong> Some formats allow other types of data to be embedded within their structures.</p><p>These characteristics are not inherently vulnerabilities. However, they can cause different parsers to make different decisions about the same file.</p><h3>The Security Problem: What Happens When Parsers Disagree?</h3><p>Polyglot files are particularly relevant to file upload systems, document processing services, and security scanners.</p><p>Imagine a web application that allows users to upload profile pictures.</p><p>The application checks the file extension and accepts files ending in .jpg.</p><p>However, the extension, MIME type, or magic bytes alone are not sufficient to establish that the file is safe.</p><p>Consider this scenario:</p><ol><li>A user uploads a file.</li><li>The application identifies it as a JPEG.</li><li>The file is sent to a preview service.</li><li>The preview service uses a different parser.</li><li>The two components may interpret the same file differently.</li></ol><p>Such inconsistencies can introduce security risks.</p><p>Potential risks include:</p><ul><li>File Upload Vulnerabilities</li><li>MIME Type Spoofing</li><li>Parser Inconsistencies</li><li>Content-Type Confusion</li><li>Security Scanner Evasion</li><li>Unexpected File Processing Behavior</li></ul><p>The important question is not only what a file claims to be, but also how every component in the system processes it.</p><h3>File Upload Security: Why Are Extension Checks Not Enough?</h3><p>Consider a simple validation check in a PHP application:</p><pre>$extension = pathinfo($filename, PATHINFO_EXTENSION);<br><br>if ($extension === &#39;jpg&#39;) {<br>    // Accept file<br>}</pre><p>This is not sufficient protection.</p><p>A user can change a filename and its extension without changing the underlying file content.</p><p>A more secure file acceptance process should consist of multiple validation layers.</p><h4>1. Extension Allowlist</h4><p>Only extensions that the application actually supports should be accepted.</p><p>For example;</p><pre>$allowedExtensions = [&#39;jpg&#39;, &#39;jpeg&#39;, &#39;png&#39;];<br>$extension = strtolower(<br>    pathinfo($filename, PATHINFO_EXTENSION)<br>);<br>if (!in_array($extension, $allowedExtensions, true)) {<br>    throw new RuntimeException(&#39;Unsupported file extension&#39;);<br>}</pre><h4>2. MIME Type Validation</h4><p>The MIME type should not be trusted solely because it was provided by the client.</p><p>On the PHP side, tools such as finfo can estimate the MIME type based on file content.</p><pre>$finfo = new finfo(FILEINFO_MIME_TYPE);<br>$mimeType = $finfo-&gt;file($tmpFile);<br>$allowedMimeTypes = [<br>    &#39;image/jpeg&#39;,<br>    &#39;image/png&#39;<br>];<br>if (!in_array($mimeType, $allowedMimeTypes, true)) {<br>    throw new RuntimeException(&#39;Invalid MIME type&#39;);<br>}</pre><p>This check alone still does not prove that a file is valid or safe.</p><h4>3. File Signature Validation</h4><p>The initial bytes of a file can be inspected to determine whether they are consistent with the expected format.</p><p>However, signature validation is only one signal. The entire file must still conform to the format’s structural requirements.</p><h4>4. Actual Parsing</h4><p>The file should be processed using a trusted decoder or parser for the supported format.</p><p>For example, instead of simply identifying a file as image/jpeg, an application should attempt to decode it using a suitable image-processing library.</p><h4>5. Secure Storage</h4><p>Uploaded files should preferably be stored outside the web root.</p><p>Additional precautions include:</p><ul><li>Generate filenames on the server side.</li><li>Never trust user-controlled file paths.</li><li>Prevent uploaded files from being executed directly.</li><li>Apply file-size and resource-consumption limits.</li><li>Serve files through controlled access mechanisms.</li></ul><h3>Image Re-encoding: An Additional Security Layer</h3><p>One useful approach for image upload systems is image re-encoding.</p><p>The idea is straightforward:</p><p>Instead of storing the uploaded file as-is, a trusted image decoder processes it. The resulting pixel data is then encoded into a newly generated image file.</p><pre>Original Uploaded File<br>          |<br>          v<br>    Image Decoder<br>          |<br>          v<br>    Decoded Pixels<br>          |<br>          v<br>    Image Encoder<br>          |<br>          v<br>Newly Generated Image</pre><p>This can prevent unsupported metadata or additional content from being carried into the newly generated image.</p><p>However, re-encoding does not guarantee complete security. The decoder itself is part of the attack surface. Therefore, applications should use updated libraries, enforce resource limits, and perform processing in an isolated environment whenever possible.</p><h3>Three Real-World Scenarios</h3><h4>Scenario 1 — Profile Picture Upload</h4><p>A social media platform allows users to upload profile pictures.</p><p>The system validates only the file extension.</p><p>Risk: Unexpected file content or parser behavior.</p><p>Solution: Layered validation, actual decoder checks, and secure storage.</p><h4>Scenario 2 — Document Preview Service</h4><p>An application accepts PDF, DOCX, and image files. Another service converts these files into previews.</p><p>Risk: The upload service and preview service may interpret the same file differently.</p><p>Solution: Consistent format policies, isolated parsers, and content validation across components.</p><h4>Scenario 3 — Antivirus and Security Scanner</h4><p>A file is inspected by a security scanner and then processed by another application.</p><p>Risk: The content analyzed by the scanner may not be interpreted in exactly the same way by the application.</p><p>Solution: Consistent analysis policies, updated parsers, and layered security controls.</p><p>This leads to an important engineering principle:</p><p><strong>Security is not only about validating input. It is also about ensuring that every component interprets that input consistently.</strong></p><h3>Polyglot File Analyzer: Let’s Inspect a File!</h3><p>One of the best ways to understand polyglot files is to inspect their underlying content.</p><p>Using a Hex Editor or a file analysis tool, we can examine the byte-level structure of a file.</p><p>A file analyzer can provide information such as:</p><ul><li>File name and extension</li><li>File size</li><li>Detected MIME type</li><li>Initial hexadecimal bytes</li><li>Recognized file signatures</li><li>Extension and content mismatch</li><li>Format validation results</li></ul><p>For example;</p><pre>File Name: sample.jpg<br>Extension: jpg<br>Detected MIME: image/jpeg<br>Recognized Signature:<br>JPEG<br>Additional Indicators:<br>Another format-like structure detected<br>Analysis:<br>Multiple format indicators found.<br>Warning:<br>This result does not prove that the<br>file is a valid polyglot or that it is malicious.</pre><p>There is an important distinction here:</p><p>Finding multiple format signatures inside a file does not mean that the file is actually valid in multiple formats.</p><p>Each format’s structural requirements must be validated by an appropriate parser.</p><h3>How to Defend Against Polyglot Files</h3><p>A secure file upload architecture should never rely on a single validation mechanism.</p><p>Recommended security practices:</p><ul><li>Use an extension allowlist.</li><li>Never trust client-provided MIME types.</li><li>Perform content-based MIME detection.</li><li>Treat magic-byte checks as supporting evidence, not proof.</li><li>Validate files with actual parsers or decoders.</li><li>Reject unsupported formats.</li><li>Store uploaded files outside the web root.</li><li>Generate random filenames on the server side.</li><li>Never execute uploaded files directly.</li><li>Apply file-size and resource-consumption limits.</li><li>Keep parser and decoder libraries updated.</li><li>Isolate file-processing services whenever possible.</li><li>Use malware scanning and Content Disarm and Reconstruction (CDR) when appropriate.</li></ul><h3>Conclusion: A File Is More Than Its Extension</h3><p>Polyglot files are an interesting example of how file formats and parsers work.</p><p>A file extension tells us what a file appears to be. Magic bytes provide additional information about its format. However, neither one can independently prove that a file is valid, harmless, or safe.</p><p>In modern software systems, file security is not simply about checking filenames. We also need to understand which components process the file, which parsers they use, and under what conditions the content is handled.</p><p><strong>A file extension tells you what a file claims to be. Its bytes tell you more. But neither one can guarantee that a file is safe.</strong></p><p>We should evaluate files not only by their names, but also by their content and behavior throughout the system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ebfb1eedb26" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/one-file-multiple-identities-polyglot-files-file-format-ambiguity-security-risks-5ebfb1eedb26">One File, Multiple Identities: Polyglot Files, File Format Ambiguity &amp; Security Risks</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tek Dosya, Birden Fazla Kimlik]]></title>
            <link>https://aydinkml.medium.com/tek-dosya-birden-fazla-kimlik-dcce6e36f5dc?source=rss-90d9cb5e14f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcce6e36f5dc</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[dosya-işlemleri]]></category>
            <category><![CDATA[application-security]]></category>
            <category><![CDATA[siber-güvenlik]]></category>
            <category><![CDATA[polygot]]></category>
            <dc:creator><![CDATA[Kemal Aydın]]></dc:creator>
            <pubDate>Thu, 26 Nov 2026 14:01:02 GMT</pubDate>
            <atom:updated>2026-11-26T14:01:02.328Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAiyV8jP4EZ-qIdpSVUHjA.png" /></figure><h3>Bir dosya aynı anda birden fazla dosya formatı olabilir mi?</h3><p>Bilgisayarlarımızda her gün onlarca farklı dosya formatıyla çalışıyoruz. JPEG görseller, PDF belgeler, ZIP arşivleri ve JSON dosyaları. Genellikle bir dosyanın uzantısına bakarak ne tür bir içerik barındırdığını anlayabileceğimizi düşünürüz.</p><p>Peki ya bir dosya aynı anda birden fazla formatın kurallarına uyabiliyorsa?</p><p>Bir uygulama tarafından JPEG olarak algılanan bir dosya, başka bir uygulama tarafından farklı bir format olarak yorumlanabilir mi?</p><p>Cevap: Evet.</p><p>Bu ilginç davranışın arkasında <strong>Polyglot Files (Poliglot Dosyalar)</strong> kavramı bulunuyor. Bu yazıda dosya formatlarının nasıl tanımlandığını, farklı parser’ların aynı dosyayı neden farklı yorumlayabildiğini ve bu durumun yazılım güvenliği açısından neden önemli olduğunu inceleyeceğiz.</p><h3>Bilgisayarlar Dosya Formatlarını Nasıl Tanır?</h3><p>Bir dosyanın türünü belirlemek için yalnızca dosya uzantısına bakmak yeterli değildir.</p><p>Örneğin;</p><ul><li>photo.jpg</li><li>document.pdf</li><li>archive.zip</li><li>data.json</li></ul><p>Dosya uzantıları işletim sistemine ve uygulamalara dosyanın nasıl ele alınabileceği konusunda bilgi verir. Ancak uzantı, dosyanın gerçek içeriğini garanti etmez.</p><p>Dosya formatlarını tanımlamak için kullanılan bazı temel yöntemler vardır.</p><h4>File Extension</h4><p>Dosya adının sonundaki uzantıdır. Örneğin .jpg, .pdf veya .zip. Bu bilgi kolayca değiştirilebilir. Bir dosyanın adını document.pdf olarak değiştirmek, dosyanın gerçekten PDF olduğu anlamına gelmez.</p><h4>MIME Type</h4><p>MIME type, içeriğin türünü tanımlamak için kullanılan standart bir gösterimdir.</p><p>Örnekler;</p><pre><strong>+-----------------------------+<br>| Format   | MIME Type        |<br>+-----------------------------+</strong><br>| JPEG     | image/jpeg       |<br>| PNG      | image/png        | <br>| PDF      | application/pdf  |<br>| ZIP      | application/zip  |<br>| JSON     | application/json |<br>+-----------------------------+</pre><h4>HTTP üzerinden dosya gönderirken Content-Type başlığıyla sıkça karşılaşırız.</h4><p>Ancak MIME type da her zaman güvenilir değildir. Özellikle istemciden gelen MIME bilgisi kullanıcı tarafından değiştirilebilir.</p><h4>Magic Bytes (File Signatures)</h4><p>Dosyaların belirli formatlara özgü başlangıç byte’ları bulunabilir. Bunlara magic bytes veya file signatures denir.</p><p>Bazı örnekler;</p><pre><strong>+------------------------------+<br>| Format   | Signature         |<br>+------------------------------+</strong><br>| JPEG     | FF D8 FF          |<br>| PNG      | 89 50 4E 47       | <br>| PDF      | 25 50 44 46 (%PDF)|<br>| ZIP      | 50 4B 03 04       | <br>+------------------------------+</pre><p>Bu imzalar dosyanın hangi formatta olabileceği hakkında önemli ipuçları verir.</p><p>Ancak burada kritik bir ayrıntı var: Bir dosyanın beklenen magic bytes değerine sahip olması, onun geçerli veya güvenli olduğunu kanıtlamaz.</p><h3>Parser Nedir ve Neden Önemlidir?</h3><p>Bir parser, belirli bir veri formatını okuyup o formatın kurallarına göre yorumlayan yazılım bileşenidir.</p><p>Örneğin:</p><ul><li>PDF Reader, PDF formatını yorumlar.</li><li>Image Decoder, JPEG veya PNG verilerini çözümler.</li><li>ZIP Reader, arşiv yapısını okur.</li><li>Browser, HTML ve diğer web içeriklerini işler.</li></ul><p>Aynı byte dizisi, farklı parser’lar tarafından farklı kurallara göre değerlendirilebilir.</p><p>Bunun nedeni her formatın farklı bir yapıya, başlangıç ve bitiş işaretlerine, metadata alanlarına ve veri yorumlama kurallarına sahip olmasıdır.</p><p>İşte bu farklılıklar Polyglot Files kavramının temelini oluşturur.</p><h3>Polyglot File Nedir?</h3><p>Polyglot File, birden fazla dosya formatının yapısal kurallarına uyacak şekilde hazırlanmış ve farklı uygulamalar tarafından farklı biçimlerde yorumlanabilen dosyadır.</p><p>“Polyglot” kelimesi birden fazla dil konuşabilen kişi anlamına gelir. Yazılım dünyasında ise birden fazla formatın dilini konuşabilen dosyaları ifade eder.</p><p>Kavramsal olarak bir dosyanın yapısını şöyle düşünebiliriz:</p><pre>+------------------------------+<br>| Format A Header              |<br>+------------------------------+<br>| Shared / Compatible Content  |<br>+------------------------------+<br>| Format A Data                |<br>+------------------------------+<br>| Format B Structure / Data    |<br>+------------------------------+</pre><p>Buradaki önemli nokta, dosyanın farklı bölümlerinin farklı formatların kurallarına uygun olabilmesidir.</p><p>Bir uygulama dosyayı birinci formatın kurallarına göre okurken başka bir uygulama farklı bir yapıyı esas alabilir.</p><p>Bu nedenle aynı dosya, farklı yazılımlarda farklı davranışlar gösterebilir.</p><blockquote><strong>Önemli:</strong> Her dosyanın sonuna başka bir formatın verisini eklemek otomatik olarak geçerli bir polyglot dosya oluşturmaz. Dosyanın her iki formatın da yapısal gereksinimlerini karşılaması gerekir.</blockquote><h3>Polyglot Files Nasıl Ortaya Çıkar?</h3><p>Polyglot dosyaların oluşabilmesini sağlayan bazı teknik özellikler vardır:</p><p><strong>Format Flexibility:</strong> Bazı dosya formatları ek metadata, yorum alanları veya belirli bölgelerde fazladan veri bulunmasına izin verir.</p><p><strong>Trailing Data:</strong> Bazı parser’lar formatın beklenen içeriğini okuduktan sonra dosyanın geri kalanını dikkate almayabilir.</p><p><strong>Parser Differences:</strong> Farklı yazılımlar aynı formatın kurallarını farklı seviyelerde katı biçimde uygulayabilir.</p><p><strong>Embedded Content:</strong> Bazı formatlar başka veri türlerini kendi yapıları içerisinde barındırabilir.</p><p>Bu özellikler her zaman bir güvenlik açığı anlamına gelmez. Ancak farklı parser’ların aynı dosya üzerinde farklı kararlar vermesine neden olabilir.</p><h3>Güvenlik Problemi: Parser’lar Aynı Fikirde Değilse Ne Olur?</h3><p>Polyglot dosyalar özellikle dosya yükleme sistemleri, doküman işleme servisleri ve güvenlik tarayıcıları açısından önemlidir.</p><p>Bir web uygulamasının kullanıcıdan profil fotoğrafı kabul ettiğini düşünelim.</p><p>Uygulama dosyanın uzantısını kontrol ediyor ve .jpg olan dosyaları kabul ediyor.</p><p>Ancak dosyanın uzantısı, MIME type bilgisi veya magic bytes kontrolü tek başına yeterli değildir.</p><p>Örneğin:</p><ol><li>Kullanıcı bir dosya yükler.</li><li>Uygulama dosyayı JPEG olarak değerlendirir.</li><li>Dosya bir önizleme servisine gönderilir.</li><li>Önizleme servisi farklı bir parser kullanır.</li><li>İki bileşen aynı dosyayı farklı yorumlayabilir.</li></ol><p>Bu tür tutarsızlıklar güvenlik açısından risk oluşturabilir.</p><p>Karşılaşılabilecek riskler:</p><ul><li>File Upload Vulnerabilities</li><li>MIME Type Spoofing</li><li>Parser Inconsistencies</li><li>Content-Type Confusion</li><li>Security Scanner Evasion</li><li>Unexpected File Processing Behavior</li></ul><p>Burada önemli olan yalnızca dosyanın ne olduğuna karar vermek değil, sistemin tüm bileşenlerinin dosyayı nasıl işlediğini anlamaktır.</p><h3>File Upload Security: Neden Sadece Uzantı Kontrolü Yeterli Değil?</h3><p>Bir PHP uygulamasında aşağıdaki gibi bir kontrol yapıldığını düşünelim:</p><pre>$extension = pathinfo($filename, PATHINFO_EXTENSION);<br><br>if ($extension === &#39;jpg&#39;) {<br>    // Accept file<br>}</pre><p>Bu kontrol tek başına güvenli değildir.</p><p>Çünkü kullanıcı dosyanın adını ve uzantısını değiştirebilir.</p><p>Daha güvenli bir dosya kabul süreci birden fazla kontrol katmanından oluşmalıdır.</p><h4>1. Extension Allowlist</h4><p>Yalnızca uygulamanın gerçekten desteklediği dosya uzantılarına izin verilmelidir.</p><p>Örneğin:</p><pre>$allowedExtensions = [&#39;jpg&#39;, &#39;jpeg&#39;, &#39;png&#39;];<br><br>$extension = strtolower(<br>    pathinfo($filename, PATHINFO_EXTENSION)<br>);<br>if (!in_array($extension, $allowedExtensions, true)) {<br>    throw new RuntimeException(&#39;Unsupported file extension&#39;);<br>}</pre><h4>2. MIME Type Validation</h4><p>Dosyanın MIME type bilgisi, yalnızca istemcinin gönderdiği değere güvenilerek belirlenmemelidir.</p><p>PHP tarafında finfo gibi araçlarla dosyanın içeriğine dayalı bir MIME tahmini yapılabilir.</p><pre>$finfo = new finfo(FILEINFO_MIME_TYPE);<br>$mimeType = $finfo-&gt;file($tmpFile);<br><br>$allowedMimeTypes = [<br>    &#39;image/jpeg&#39;,<br>    &#39;image/png&#39;<br>];<br>if (!in_array($mimeType, $allowedMimeTypes, true)) {<br>    throw new RuntimeException(&#39;Invalid MIME type&#39;);<br>}</pre><p>Bu kontrol de tek başına dosyanın geçerli veya güvenli olduğunu kanıtlamaz.</p><h4>3. File Signature Validation</h4><p>Dosyanın başlangıç byte’ları kontrol edilerek beklenen formatla uyumlu olup olmadığı değerlendirilebilir.</p><p>Ancak magic bytes kontrolü de tek başına yeterli değildir. Dosyanın tamamının ilgili formatın yapısına uygun olması gerekir.</p><h4>4. Actual Parsing</h4><p>Dosya, desteklenen formatın güvenilir bir decoder veya parser bileşeniyle gerçekten açılabilmelidir.</p><p>Örneğin bir görsel dosyasını yalnızca image/jpeg olarak tanımlamak yerine gerçek bir görüntü kütüphanesiyle decode etmeyi denemek daha anlamlıdır.</p><h4>5. Secure Storage</h4><p>Yüklenen dosyalar mümkünse web root dışında saklanmalıdır.</p><p>Ek olarak:</p><ul><li>Dosya isimleri sunucu tarafında oluşturulmalıdır.</li><li>Kullanıcı tarafından belirlenen dosya yollarına güvenilmemelidir.</li><li>Dosyalar doğrudan çalıştırılabilir olmamalıdır.</li><li>Dosya boyutu ve işlem kaynakları sınırlandırılmalıdır.</li><li>Dosyalar erişim kontrolüyle sunulmalıdır.</li></ul><h3>Image Re-encoding: Ek Bir Güvenlik Katmanı</h3><p>Özellikle görsel yükleme sistemlerinde kullanılabilecek yaklaşımlardan biri image re-encoding işlemidir.</p><p>Temel mantık şudur:</p><p>Kullanıcıdan gelen dosyayı olduğu gibi saklamak yerine, güvenilir bir görüntü decoder ile açarız. Ardından elde edilen piksel verilerini yeni bir görsel dosyası olarak encode ederiz.</p><pre>Original Uploaded File<br>          |<br>          v<br>    Image Decoder<br>          |<br>          v<br>    Decoded Pixels<br>          |<br>          v<br>    Image Encoder<br>          |<br>          v<br> Newly Generated Image</pre><p>Bu yöntem, orijinal dosyadaki desteklenmeyen metadata veya ek içeriklerin yeni dosyaya taşınmasını önleyebilir.</p><p>Ancak re-encoding de mutlak güvenlik sağlamaz. Decoder’ın kendisi de saldırı yüzeyidir. Bu nedenle güncel kütüphaneler kullanılmalı, kaynak limitleri uygulanmalı ve işlem mümkünse izole bir ortamda yapılmalıdır.</p><h3>Gerçek Hayattan Üç Senaryo</h3><h4>Senaryo 1 — Profil Resim Yüklemesi</h4><p>Bir sosyal medya platformu kullanıcıların profil fotoğrafı yüklemesine izin veriyor.</p><p>Sistem yalnızca dosya uzantısını kontrol ediyor.</p><p>Risk: Beklenmeyen dosya içerikleri veya parser davranışları.</p><p>Çözüm: Çok katmanlı doğrulama, gerçek decoder kontrolü ve güvenli storage.</p><h4>Senaryo 2 — Dosya Görüntüleme Servisi</h4><p>Bir uygulama PDF, DOCX ve görsel dosyalarını kabul ediyor. Dosyalar daha sonra farklı bir servis tarafından önizlemeye dönüştürülüyor.</p><p>Risk: Upload servisi ile preview servisi aynı dosyayı farklı yorumlayabilir.</p><p>Çözüm: Her bileşende tutarlı format politikası, izole parser kullanımı ve dosya içeriğinin doğrulanması.</p><h4>Senaryo 3 — Antivirus and Güvenlik Taraması</h4><p>Bir dosya güvenlik tarayıcısından geçiriliyor ve ardından başka bir uygulamada işleniyor.</p><p>Risk: Tarayıcının analiz ettiği içerik ile uygulamanın yorumladığı içerik arasında farklılık oluşabilir.</p><p>Çözüm: Aynı dosya üzerinde tutarlı analiz politikaları, güncel parser’lar ve çok katmanlı güvenlik kontrolleri.</p><h3>Polyglot Dosya Analizi</h3><p>Polyglot dosyaları daha iyi anlamanın en iyi yollarından biri dosyanın içeriğini incelemektir.</p><p>Bir Hex Editor veya dosya analiz aracı kullanarak dosyanın byte seviyesindeki yapısını gözlemleyebiliriz.</p><p>Bir dosya analiz aracında şu bilgiler incelenebilir:</p><ul><li>File name and extension</li><li>File size</li><li>Detected MIME type</li><li>Initial hexadecimal bytes</li><li>Recognized file signatures</li><li>Extension and content mismatch</li><li>Format validation results</li></ul><p>Örneğin;</p><pre>File Name: sample.jpg<br>Extension: jpg<br>Detected MIME: image/jpeg<br><br>Recognized Signature:<br>JPEG<br><br>Additional Indicators:<br>Another format-like structure detected<br><br>Analysis:<br>Multiple format indicators found.<br><br>Warning:<br>This result does not prove that the<br>file is a valid polyglot or that it is malicious.</pre><p>Burada özellikle önemli bir ayrım var:</p><p>Bir dosyada birden fazla formatın imzasını bulmak, dosyanın gerçekten iki geçerli format olduğu anlamına gelmez.</p><p>Bunun için her formatın yapısal kurallarının ilgili parser tarafından doğrulanması gerekir.</p><h3>Polyglot Dosyalara Karşı Nasıl Daha Güvenli Yükleme Sistemi Oluşturulur?</h3><p>Güvenli bir dosya yükleme mimarisi tek bir kontrole dayanmamalıdır.</p><p>Önerilen güvenlik yaklaşımı:</p><ul><li>Dosya uzantısı allowlist kullan.</li><li>İstemciden gelen MIME type değerine güvenme.</li><li>İçerik tabanlı MIME tespiti yap.</li><li>Magic bytes kontrolünü yardımcı bir sinyal olarak değerlendir.</li><li>Dosyayı gerçek parser veya decoder ile doğrula.</li><li>Desteklenmeyen formatları reddet.</li><li>Dosyaları web root dışında sakla.</li><li>Sunucu tarafında rastgele dosya isimleri oluştur.</li><li>Dosyaları doğrudan çalıştırma.</li><li>Dosya boyutu ve kaynak kullanımına limit koy.</li><li>Parser ve decoder kütüphanelerini güncel tut.</li><li>Dosya işleme servislerini mümkün olduğunca izole et.</li><li>Gerekli durumlarda malware scanning ve Content Disarm and Reconstruction (CDR) kullan.</li></ul><p>Polyglot dosyalar, dosya formatlarının ve parser’ların nasıl çalıştığını anlamak için oldukça ilginç bir örnektir.</p><p>Bir dosyanın uzantısı bize onun ne olduğunu söyler gibi görünür. Magic bytes ise format hakkında daha fazla bilgi verir. Ancak bunların hiçbiri tek başına dosyanın geçerli, zararsız veya güvenli olduğunu kanıtlamaz.</p><p>Modern yazılım sistemlerinde dosya güvenliği, yalnızca dosyanın adını kontrol etmekten ibaret değildir. Dosyanın hangi bileşen tarafından, hangi parser ile ve hangi koşullarda işleneceğini de anlamak gerekir.</p><p>Dosyaları yalnızca isimlerine göre değil, içeriklerine ve sistem içerisindeki davranışlarına göre değerlendirmeliyiz.</p><p>Başka bir blog yazısında görüşmek üzere!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcce6e36f5dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bir görselin ardında neler saklı? Konumuz görüntü işleme.]]></title>
            <link>https://aydinkml.medium.com/bir-g%C3%B6rselin-ard%C4%B1nda-neler-sakl%C4%B1-konumuz-g%C3%B6r%C3%BCnt%C3%BC-i%C5%9Fleme-a09624c88f9a?source=rss-90d9cb5e14f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a09624c88f9a</guid>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[mühendislik]]></category>
            <category><![CDATA[görüntü-i̇şleme]]></category>
            <category><![CDATA[yapay-zeka-uygulamaları]]></category>
            <dc:creator><![CDATA[Kemal Aydın]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 10:46:01 GMT</pubDate>
            <atom:updated>2026-11-12T10:46:01.647Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Bir fotoğrafa baktığımızda gördüğümüz şey aslında milyonlarca küçük sayının bir araya gelmiş hali. Peki bu sayılarla neler yapabiliriz?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*--IFtp_BgYjI0dJCptTJNQ.png" /></figure><h3>Merhaba, pikseller!</h3><p>Bir fotoğraf çektiğimizde gördüğümüz şey genellikle bir manzara, bir insan, bir nesne veya güzel bir anıdır. Fakat bilgisayar için durum biraz farklıdır. Bilgisayar fotoğrafa baktığında bir manzara görmez; sayılarla dolu bir matris görür. İşte görüntü işleme tam olarak burada devreye giriyor. Yüksek lisans sürecimde Görüntü İşleme ve Analizi dersiyle birlikte bu alanı daha yakından keşfetmeye başladım. Teorik konuların oldukça ilgi çekici olduğunu fark ettim. Ancak asıl eğlenceli kısmın, bir algoritmayı uygulayıp görüntünün nasıl değiştiğini görmek olduğunu söyleyebilirim.</p><p>Bu yazıda görüntü işlemenin temel kavramlarını birkaç örnek üzerinden inceleyeceğiz. Üstelik yalnızca okumakla yetinmeyeceğiz; kendi görsellerimizi de işleyeceğiz.</p><p>Hazırsanız piksellerin dünyasına dalalım!</p><h3>1. Görüntü dediğimiz şey aslında nedir?</h3><p>Dijital bir görüntü, piksellerden oluşur. Her piksel, görüntünün belirli bir konumundaki renk veya parlaklık bilgisini taşır.</p><p>Örneğin gri tonlamalı bir görüntüde piksel değerleri genellikle 0 ile 255 arasındadır:</p><p>0: Siyah — 255: Beyaz — 128: Orta gri</p><p>RGB görüntülerde ise her piksel üç farklı kanaldan oluşur:</p><ul><li>R: Red (Kırmızı)</li><li>G: Green (Yeşil)</li><li>B: Blue (Mavi)</li></ul><p>Örneğin (255, 0, 0) değeri saf kırmızıyı ifade eder.</p><p>Yani bilgisayar için bir fotoğraf, aslında üç boyutlu bir veri dizisi olabilir: yükseklik, genişlik ve renk kanalları.</p><h3>2. İlk işlemimiz: Grayscale (Gri Tonlama)</h3><p>Bir görüntüyü gri tonlamaya çevirmek, görüntü işlemenin en temel adımlarından biridir.</p><p>Peki neden renkleri kaybedelim?</p><p>Çünkü birçok görüntü işleme algoritması renk bilgisinden ziyade parlaklık bilgisiyle ilgilenir. Kenar tespiti, eşikleme ve bazı segmentasyon yöntemleri için gri tonlamalı görüntüler oldukça kullanışlıdır.</p><p>Yaygın kullanılan dönüşüm formülü şöyledir:</p><p>Gray = 0.299R + 0.587G + 0.114B</p><p>Bu katsayılar insan gözünün yeşil renge daha duyarlı olmasını da hesaba katar.</p><p><strong>Küçük bir deney:</strong> Kendi fotoğrafınızı gri tonlamaya çevirin. Sizce renkler kaybolduğunda görüntünün detayları da kayboluyor mu?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cn35YIrQ65Nwpwpxlk1r8w.png" /><figcaption>Gri Tonlama Uygulanmış Görsel Örneği</figcaption></figure><h3>3. Kontrast iyileştirme: Görüntüye biraz hayat verelim</h3><p>Bazen çektiğimiz fotoğraflar fazla karanlık, soluk veya düşük kontrastlı olabilir. Contrast Stretching (Kontrast Germe), görüntüdeki piksel değerlerini daha geniş bir yoğunluk aralığına yayarak kontrastı artırmayı amaçlar.</p><p>Temel formülü: I_new = (I - I_min) × 255 / (I_max - I_min)</p><p>Burada;</p><ul><li>I: Mevcut piksel değeri</li><li>I_min: Görüntüdeki minimum değer</li><li>I_max: Görüntüdeki maksimum değer</li><li>I_new: Yeni piksel değeri</li></ul><p>Örneğin görüntüdeki piksel değerleri 50 ile 180 arasında sıkışmışsa, bu değerleri 0 ile 255 arasına yayabiliriz.</p><p>Sonuç? Daha belirgin aydınlık ve karanlık bölgeler!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*44f--KK9DAGBQQ6zcj8iQw.png" /><figcaption>Kontrast İyileştirme Uygulanmış Görsel Örneği</figcaption></figure><h3>4. Histogram Equalization: Pikselleri biraz dağıtalım</h3><p>Histogram, görüntüdeki piksel yoğunluklarının dağılımını gösterir. Yatay eksende piksel yoğunlukları, dikey eksende ise bu yoğunluklara sahip piksel sayısı bulunur. Histogram Equalization (Histogram Eşitleme), görüntünün kontrastını iyileştirmek amacıyla yoğunluk dağılımını yeniden düzenler. Özellikle düşük kontrastlı görüntülerde faydalı olabilir.</p><blockquote>Ancak küçük bir uyarı: Histogram eşitleme her görüntüyü güzelleştirmez. Bazen gürültüyü de belirginleştirebilir. Yani fotoğrafın güzelleşmesi garanti değil; algoritmanın özgüveni biraz fazla olabilir!</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FUU0ZB7AVceW1aWKXAn8Fw.png" /><figcaption>Histogram Eşitleme Uygulanmış Görsel Örneği</figcaption></figure><h3>5. Noise Reduction: Görüntüdeki gürültüyü temizlemek</h3><p>Dijital görüntülerde sensör kaynaklı veya aktarım sırasında oluşan gürültüler bulunabilir. Bu gürültüler görüntünün kalitesini düşürür ve sonraki analiz aşamalarını olumsuz etkileyebilir.</p><p>İki temel filtreyi ele alalım;</p><p><strong>Mean Filter (Ortalama Filtresi)</strong></p><p>Bir pikselin yeni değeri, komşuluğundaki piksellerin ortalaması alınarak hesaplanır. Avantajı basit ve hızlı olmasıdır. Dezavantajı ise kenarları bulanıklaştırabilmesidir.</p><p><strong>Median Filter (Medyan Filtresi)</strong></p><p>Komşuluktaki piksel değerleri sıralanır ve ortadaki değer seçilir. Özellikle Salt &amp; Pepper Noise olarak bilinen siyah-beyaz noktasal gürültüyü temizlemede oldukça başarılıdır.</p><p>Kısacası ortalama filtre komşularının ortalamasını alırken, medyan filtre komşuların ortanca değerini seçer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KHegJalozfuAPkSH_Jhldg.png" /><figcaption>Mean Filter Uygulanmış Görsel Örneği</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Je6P-q8wgZql9-Q4ye8XtA.png" /><figcaption>Median Filter Uygulanmış Görsel Örneği</figcaption></figure><h3>6. Thresholding: Görüntüyü ikiye ayırmak</h3><p>Thresholding (Eşikleme), bir görüntüdeki pikselleri belirli bir eşik değerine göre sınıflandırır.</p><p>Örneğin:</p><ul><li>Piksel değeri eşikten büyükse beyaz,</li><li>Piksel değeri eşikten küçük veya eşitse siyah yapılır.</li></ul><p>Bu yöntem nesne tespiti ve görüntü segmentasyonu gibi alanlarda kullanılabilir.</p><p>Örneğin bir belge fotoğrafındaki yazıları arka plandan ayırmak istediğimizi düşünelim. Doğru eşik değeriyle oldukça başarılı sonuçlar elde edebiliriz.</p><p>Fakat her görüntü için aynı eşik değerini kullanmak doğru değildir. Işık koşulları ve görüntü dağılımı sonucu doğrudan etkiler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AS_16-xIYFFZY1rOHd2JDA.png" /><figcaption>Thresholdig Uygulanmış Görsel Örneği</figcaption></figure><h3>7. Kenar tespiti: Nesnelerin sınırlarını bulmak</h3><p>Bir görüntüdeki nesnelerin sınırlarını belirlemek, görüntü analizinin önemli adımlarından biridir.</p><p>Sobel operatörü, yatay ve dikey yoğunluk değişimlerini hesaplayarak kenarları belirlemeye yardımcı olur.</p><p>Canny Edge Detection ise gürültü azaltma, gradyan hesaplama, non-maximum suppression ve hysteresis thresholding gibi aşamalarla daha gelişmiş bir kenar tespit yaklaşımı sunar.</p><p>Bu teknikler nesne tanıma, tıbbi görüntüleme ve endüstriyel kalite kontrol gibi birçok alanda kullanılır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLt5a4IdBpi9mfTSd2H5LA.png" /><figcaption>Kenar Tespiti Uygulanmış Görsel Örneği</figcaption></figure><h3>8. Peki bunları nerelerde kullanıyoruz?</h3><p>Görüntü işleme yalnızca fotoğraf düzenlemekten ibaret değil.</p><ul><li><strong>Tıp:</strong> MR, tomografi ve röntgen görüntülerinin analizi.</li><li><strong>Otonom araçlar:</strong> Şerit, trafik işareti ve yaya tespiti.</li><li><strong>Güvenlik:</strong> Yüz ve nesne tanıma.</li><li><strong>Tarım:</strong> Bitki hastalıklarının ve ürün kalitesinin analizi.</li><li><strong>Endüstri:</strong> Üretim hattında hatalı ürün tespiti.</li><li><strong>Uydu görüntüleme:</strong> Arazi sınıflandırması ve değişim analizi.</li></ul><p>Günümüzde yapay zeka ve derin öğrenme yöntemleriyle birlikte görüntü işleme çok daha geniş bir uygulama alanına sahip.</p><h3><strong>Gerçek Hayattan Bir Uygulama: Kimlik Kartından Otomatik Bilgi Okuma (ID OCR)</strong></h3><p>Şimdi biraz daha gerçek dünyaya yaklaşalım.</p><p>Bir bankanın mobil uygulamasını kullandığımızı düşünelim. Hesap açmak istiyoruz ve uygulama bizden kimlik kartımızın fotoğrafını çekmemizi istiyor. Fotoğrafı çekiyoruz ve birkaç saniye içerisinde uygulama adımızı, soyadımızı, doğum tarihimizi ve kimlik numaramızı otomatik olarak dolduruyor.</p><p>Peki uygulama bunu nasıl başarıyor? Kameradan gelen bir görüntü, nasıl oluyor da anlamlı verilere dönüşüyor? Aslında arka planda görüntü işleme, OCR ve veri doğrulama adımlarından oluşan bir işlem zinciri çalışıyor.</p><h4>1. Görüntünün alınması (Image Acquisition)</h4><p>İlk aşamada kullanıcıdan kimlik kartının fotoğrafı alınır.</p><p>Ancak her fotoğraf işleme için uygun değildir. Örneğin:</p><ul><li>Fotoğraf bulanık olabilir.</li><li>Kimlik kartı eğik çekilmiş olabilir.</li><li>Işık yansıması nedeniyle bazı karakterler görünmeyebilir.</li><li>Görüntü çok karanlık veya fazla aydınlık olabilir.</li><li>Kimlik kartının bir bölümü kadraj dışında kalabilir.</li></ul><p>Bu nedenle uygulama öncelikle görüntünün işlenmeye uygun olup olmadığını kontrol eder.</p><h4>2. Ön işleme (Image Preprocessing)</h4><p>Bu aşamada daha önce öğrendiğimiz görüntü işleme teknikleri devreye girer.</p><ul><li><strong>Grayscale:</strong> Renk bilgisi yerine parlaklık üzerinden işlem yapılmasını sağlar.</li><li><strong>Noise Reduction:</strong> Görüntüdeki gürültüyü azaltır.</li><li><strong>Contrast Enhancement:</strong> Karakterlerin arka plandan daha kolay ayrılmasına yardımcı olur.</li><li><strong>Thresholding:</strong> Uygun koşullarda yazı ve arka plan arasındaki farkı belirginleştirir.</li></ul><p>Fakat önemli bir nokta var: Her kimlik fotoğrafına bütün işlemleri uygulamak doğru değildir. Örneğin renkli güvenlik desenleri veya hologramlar bazı belgelerde önemli olabilir. Bu yüzden ön işleme adımları görüntünün özelliklerine göre seçilir.</p><h4>3. Perspektif düzeltme (Perspective Correction)</h4><p>Kimlik kartını tam karşıdan çekmediğimizi düşünelim. Kart görüntüde yamuk bir dörtgen gibi görünebilir. Bu durumda uygulama önce kartın köşelerini tespit eder, ardından Perspective Transformation (Perspektif Dönüşümü) uygular. Amaç, eğik görüntüyü karşıdan çekilmiş gibi dikdörtgen bir düzleme dönüştürmektir. Böylece OCR algoritmasının karakterleri tanıması kolaylaşır.</p><h4>4. Metin alanlarının bulunması (Text Detection)</h4><p>Artık elimizde daha düzgün bir kimlik görüntüsü var. Sıradaki adım, metinlerin nerede bulunduğunu tespit etmek.</p><p>Uygulama görüntüyü analiz ederek isim, soyisim, doğum tarihi ve kimlik numarası gibi alanların bulunduğu bölgeleri belirler. Bu işlem için EAST, CRAFT veya derin öğrenme tabanlı metin tespit modelleri kullanılabilir.</p><p>Örneğin:</p><ul><li>İsim alanının koordinatları: (x1, y1, x2, y2)</li><li>Soyisim alanının koordinatları: (x1, y1, x2, y2)</li><li>Doğum tarihi alanının koordinatları: (x1, y1, x2, y2)</li></ul><p>Bu koordinatlar kullanılarak ilgili bölgeler görüntüden kesilir (Region of Interest — ROI).</p><h4>5. OCR: Karakterlerin tanınması</h4><p>İşte en merak edilen kısım!</p><p>OCR (Optical Character Recognition), görüntü içerisindeki yazıları makine tarafından okunabilir metne dönüştürür.</p><p>Örneğin görüntü üzerinde şu yazı bulunuyor olsun:</p><p>AD: KEMAL</p><p>OCR algoritması bunu metin olarak elde edebilir:</p><p>AD: KEMAL</p><p>Bu işlemde Tesseract OCR, PaddleOCR veya derin öğrenme tabanlı farklı OCR modellerinden yararlanılabilir.</p><p>OCR işlemi sonucunda yalnızca metin değil, bazı sistemlerde karakterlerin veya kelimelerin konumları ve güven skorları da elde edilir.</p><h4>6. Bilgi çıkarma ve doğrulama (Information Extraction &amp; Validation)</h4><p>OCR işlemi tamamlandığında elimizde genellikle düz bir metin bulunur. Ancak uygulamanın ihtiyacı olan şey düzenli verilerdir.</p><p>Örneğin:</p><ul><li>Ad: KEMAL</li><li>Soyad: AYDIN</li><li>Doğum tarihi: 29.10.1923</li><li>Kimlik numarası: 12345678901</li></ul><p>Uygulama bu verileri belirli alanlarla eşleştirir. Bunun için alan konumları, metin etiketleri, düzenli ifadeler (Regular Expressions) ve belgeye özel kurallar kullanılabilir.</p><p>Ardından veri doğrulama işlemi gerçekleştirilir.</p><p>Örneğin tarih formatı kontrol edilir, zorunlu alanların okunup okunmadığı incelenir ve kimlik numarası için ilgili biçimsel kontroller yapılır.</p><p>Burada önemli bir ayrıntı var: OCR’nin bir metni doğru okuması, o bilginin gerçek veya belgenin geçerli olduğunu kanıtlamaz. Belge doğrulama ve kimlik doğrulama ayrı güvenlik adımlarıdır.</p><h4>7. Sonuç: Görüntüden yapılandırılmış veriye</h4><p>Bütün bu adımların sonunda sistem, fotoğrafı yapılandırılmış bir veri nesnesine dönüştürebilir.</p><p>Örneğin:</p><pre>{<br>  &quot;first_name&quot;: &quot;KEMAL&quot;,<br>  &quot;last_name&quot;: &quot;AYDIN&quot;,<br>  &quot;birth_date&quot;: &quot;1929-10-29&quot;,<br>  &quot;document_type&quot;: &quot;national_id&quot;,<br>  &quot;ocr_confidence&quot;: 0.98<br>}</pre><blockquote><em>Bu tamamen kurgusal bir örnektir. OCR güven skoru, bütün belgenin geçerli olduğuna dair bir doğrulama sonucu değildir.</em></blockquote><p>Gördüğümüz gibi, bir fotoğrafın çekilmesiyle başlayan süreç; görüntü iyileştirme, geometrik dönüşüm, metin tespiti, karakter tanıma ve veri doğrulama aşamalarından geçerek anlamlı verilere dönüşüyor.</p><p>İşte görüntü işlemenin yazılım dünyasındaki gerçek gücü tam olarak burada ortaya çıkıyor!</p><blockquote><strong>Küçük bir not:</strong> Gerçek kimlik belgeleri hassas kişisel veri içerir. Bu tür uygulamalar geliştirilirken kullanıcı onayı, veri minimizasyonu, güvenli saklama, erişim kontrolü ve KVKK gereklilikleri dikkate alınmalıdır.</blockquote><p>Görüntü işleme, ilk bakışta karmaşık matematiksel formüllerden oluşan bir alan gibi görünebilir. Ancak temel mantığı kavradığımızda oldukça eğlenceli ve üretken bir dünyaya dönüşüyor.</p><p>Bu yazımda gri tonlama, kontrast iyileştirme, histogram eşitleme, filtreleme, eşikleme ve kenar tespiti gibi temel kavramları ele aldık.</p><p>Bence bu alanı öğrenmenin en iyi yolu sadece algoritmaları okumak değil, onları gerçek görüntüler üzerinde denemek.</p><p>Çünkü bazen bir görüntüdeki küçük bir piksel değişimi, bütün sonucu değiştirebilir.</p><p>Son olarak bu blog yazısında anlattıklarımı kendi görsellerinizde deneyimlemeniz için bir github sayfası hazırladım ( <a href="https://kemalaydin.github.io/Pixel-Playground/">https://kemalaydin.github.io/Pixel-Playground/</a> ).</p><blockquote>Görseller herhangi bir sunucuda tutulmaz. Tarayıcı üzerinden kullanılır.</blockquote><p>Sevgiyle kalın.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a09624c88f9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pixels Have Stories: The Hidden World of Image Processing]]></title>
            <link>https://levelup.gitconnected.com/pixels-have-stories-the-hidden-world-of-image-processing-6b63f4766a17?source=rss-90d9cb5e14f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b63f4766a17</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[histogram-equalization]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[contrast-enhancement]]></category>
            <dc:creator><![CDATA[Kemal Aydın]]></dc:creator>
            <pubDate>Fri, 06 Nov 2026 16:50:10 GMT</pubDate>
            <atom:updated>2026-11-06T16:50:10.718Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What do we really see when we look at a photograph? Behind every image lies a world of pixels, numbers, and algorithms. Let’s explore it together!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*--IFtp_BgYjI0dJCptTJNQ.png" /></figure><h3>Hello, Pixels!</h3><p>When we look at a photograph, we usually see a landscape, a person, an object, or a beautiful memory. But computers see something completely different: a matrix of numerical values.</p><p>This is where Image Processing comes into play.</p><p>During my graduate studies, I started exploring this fascinating field through my Image Processing and Analysis course. I quickly realized that understanding the theory is important, but applying algorithms to real images and observing the results is where things get really interesting.</p><p>In this article, we will explore some fundamental image processing techniques through practical examples. And don’t worry, you won’t just be reading about them. You will also get the chance to experiment with your own images!</p><p>Let’s dive into the world of pixels!</p><h3>1. What Exactly Is a Digital Image?</h3><p>A digital image consists of small elements called pixels. Each pixel stores color or intensity information at a specific position.</p><p>In a grayscale image, pixel values typically range from 0 to 255:</p><ul><li>0 represents black.</li><li>255 represents white.</li><li>128 represents a medium shade of gray.</li></ul><p>In an RGB image, each pixel contains three color channels:</p><ul><li>R: Red</li><li>G: Green</li><li>B: Blue</li></ul><p>For example, (255, 0, 0) represents pure red.</p><p>So, a digital photograph can be represented as a multidimensional array of data containing height, width, and color channels.</p><p>Not quite as romantic as the photograph itself, right?</p><h3>2. Grayscale Conversion: Removing Color, Keeping Information</h3><p>Grayscale conversion is one of the most fundamental operations in image processing.</p><p>But why would we remove color information?</p><p>Many image processing algorithms primarily work with intensity rather than color. Grayscale images are particularly useful for edge detection, thresholding, and several segmentation techniques.</p><p>A commonly used conversion formula is:</p><p>Gray = 0.299R + 0.587G + 0.114B</p><p>These coefficients account for the human eye’s different sensitivity to RGB channels, particularly its greater sensitivity to green.</p><p><strong>Try it yourself:</strong> Convert a colorful photograph into grayscale. Do you think removing color also removes important details?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cn35YIrQ65Nwpwpxlk1r8w.png" /><figcaption>An example of a photo with greyscale applied.</figcaption></figure><h3>3. Contrast Stretching: Bringing Images to Life</h3><p>Sometimes photographs look too dark, washed out, or simply lack contrast.</p><p>Contrast Stretching expands the intensity range of an image to improve its visual appearance.</p><p>The basic formula is: I_new = (I - I_min) × 255 / (I_max - I_min)</p><p>Where:</p><ul><li>I is the original pixel intensity.</li><li>I_min is the minimum intensity.</li><li>I_max is the maximum intensity.</li><li>I_new is the transformed intensity.</li></ul><p>Imagine an image whose pixel values are concentrated between 50 and 180. We can stretch this range to cover the full interval from 0 to 255.</p><p>The result is usually a more noticeable distinction between dark and bright regions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*44f--KK9DAGBQQ6zcj8iQw.png" /><figcaption>An example of a photograph with contrast stretching applied.</figcaption></figure><h3>4. Histogram Equalization: Redistributing Pixel Intensities</h3><p>An image histogram represents the distribution of pixel intensities.</p><p>The horizontal axis represents intensity values, while the vertical axis represents the number of pixels at each intensity level.</p><p>Histogram Equalization redistributes intensity values using the cumulative distribution function (CDF) to improve image contrast.</p><p>It can be particularly useful for low-contrast images.</p><p>However, it is not a magic enhancement button. It can also amplify noise and sometimes produce visually unnatural results. Even algorithms have their bad days!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FUU0ZB7AVceW1aWKXAn8Fw.png" /><figcaption>An example of a photograph to which histogram equalisation has been applied.</figcaption></figure><h3>5. Noise Reduction: Cleaning Up Images</h3><p>Digital images may contain noise caused by camera sensors, low-light conditions, or data transmission.</p><p>Noise can reduce image quality and negatively affect subsequent analysis.</p><p>Let’s examine two common filters.</p><p><strong>Mean Filter</strong></p><p>The new value of a pixel is calculated by averaging the values of its neighboring pixels.</p><p>It is simple and computationally efficient, but it can blur edges and fine details.</p><p><strong>Median Filter</strong></p><p>The neighboring pixel values are sorted, and the middle value is selected.</p><p>Median filtering is particularly effective against Salt &amp; Pepper Noise, which appears as random black and white pixels.</p><p>In short, the mean filter calculates an average, while the median filter selects the middle value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KHegJalozfuAPkSH_Jhldg.png" /><figcaption>An example of a photograph with a Mean Filter applied.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Je6P-q8wgZql9-Q4ye8XtA.png" /><figcaption>An example of a photograph with a Median Filter applied.</figcaption></figure><h3>6. Thresholding: Separating Objects from Backgrounds</h3><p>Thresholding classifies pixels according to a predefined intensity threshold.</p><p>For example:</p><ul><li>Pixels above the threshold become white.</li><li>Pixels equal to or below the threshold become black.</li></ul><p>This technique is widely used in object detection and image segmentation.</p><p>Imagine trying to separate printed text from the background of a scanned document. A suitable threshold can make this task surprisingly simple.</p><p>Of course, one threshold value does not work equally well for every image. Lighting conditions and intensity distributions matter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AS_16-xIYFFZY1rOHd2JDA.png" /><figcaption>An example of a photograph with thresholding applied.</figcaption></figure><h3>7. Edge Detection: Finding the Boundaries</h3><p>Identifying object boundaries is an important step in image analysis.</p><p>The Sobel operator detects edges by calculating horizontal and vertical intensity changes.</p><p>Canny Edge Detection offers a more advanced approach involving several stages:</p><ul><li>Noise reduction</li><li>Gradient calculation</li><li>Non-maximum suppression</li><li>Hysteresis thresholding</li></ul><p>These techniques are used in object recognition, medical imaging, autonomous vehicles, and industrial quality inspection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLt5a4IdBpi9mfTSd2H5LA.png" /><figcaption>An example of a photograph with edge detection applied.</figcaption></figure><h3>8. Where Is Image Processing Used?</h3><p>Image processing is much more than applying filters to photographs.</p><ul><li><strong>Healthcare:</strong> MRI, CT, and X-ray image analysis.</li><li><strong>Autonomous vehicles:</strong> Lane, pedestrian, and traffic sign detection.</li><li><strong>Security:</strong> Face and object recognition.</li><li><strong>Agriculture:</strong> Plant disease detection and crop analysis.</li><li><strong>Manufacturing:</strong> Automated defect detection.</li><li><strong>Satellite imaging:</strong> Land classification and environmental monitoring.</li></ul><p>Combined with artificial intelligence and deep learning, image processing continues to expand into new applications.</p><h3>A Real-World Application: Automatic ID Card Information Extraction (ID OCR)</h3><p>Let’s move a little closer to the real world.</p><p>Imagine using a mobile banking application. You want to open a bank account, and the application asks you to take a picture of your identity card.</p><p>You take the photo, and within seconds, the application automatically fills in your first name, last name, date of birth, and identification number.</p><p>But how does this actually work? How does a photograph captured by a camera become meaningful information?</p><p>Behind the scenes, a pipeline consisting of image processing, OCR, and data validation is running.</p><h4>1. Image Acquisition</h4><p>The first step is capturing the identity card using a camera.</p><p>However, not every photograph is suitable for processing. For example:</p><ul><li>The image may be blurry.</li><li>The card may be photographed at an angle.</li><li>Light reflections may hide some characters.</li><li>The image may be too dark or overexposed.</li><li>Part of the card may be outside the frame.</li></ul><p>Therefore, the application first evaluates whether the image is suitable for further processing.</p><h4>2. Image Preprocessing</h4><p>This is where the image processing techniques discussed earlier become useful.</p><ul><li><strong>Grayscale:</strong> Simplifies processing by focusing on intensity rather than color.</li><li><strong>Noise Reduction:</strong> Removes unwanted noise from the image.</li><li><strong>Contrast Enhancement:</strong> Makes text easier to distinguish from the background.</li><li><strong>Thresholding:</strong> Can improve separation between text and background under suitable conditions.</li></ul><p>However, applying every operation to every identity document is not always a good idea. Security patterns and holographic elements may contain important information. Preprocessing should therefore depend on the document’s characteristics.</p><h4>3. Perspective Correction</h4><p>Imagine taking a photograph of an identity card from an angle. Instead of appearing as a rectangle, the card may look like a distorted quadrilateral.</p><p>The application first detects the card’s corners and then applies a Perspective Transformation.</p><p>The goal is to transform the tilted image into a rectangular, front-facing representation.</p><p>This makes it easier for OCR algorithms to recognize individual characters.</p><h4>4. Text Detection</h4><p>Now we have a properly aligned identity card image.</p><p>The next step is locating the text.</p><p>The application analyzes the image and identifies regions containing information such as first name, last name, date of birth, and identification number.</p><p>Techniques such as EAST, CRAFT, and deep-learning-based text detection models can be used.</p><p>For example:</p><ul><li>First name coordinates: (x1, y1, x2, y2)</li><li>Last name coordinates: (x1, y1, x2, y2)</li><li>Date of birth coordinates: (x1, y1, x2, y2)</li></ul><p>These coordinates are used to crop the relevant regions, also known as Regions of Interest (ROI).</p><h4>5. OCR: Recognizing Characters</h4><p>Here comes the interesting part!</p><p>OCR (Optical Character Recognition) converts text inside an image into machine-readable characters.</p><p>Imagine the following text appearing on an identity card:</p><p>FIRST NAME: KEMAL</p><p>The OCR engine can recognize and extract this text.</p><p>Tools such as Tesseract OCR, PaddleOCR, and other deep-learning-based OCR models can be used for this purpose.</p><p>Depending on the engine, the result may include recognized text, character or word positions, and confidence scores.</p><h4>6. Information Extraction and Validation</h4><p>After OCR processing, we usually have a block of plain text. However, the application needs structured information.</p><p>For example:</p><ul><li>First name: KEMAL</li><li>Last name: AYDIN</li><li>Date of birth: 29.10.1923</li><li>Identification number: 12345678901</li></ul><p>The application maps recognized text to predefined fields using text labels, region coordinates, regular expressions, and document-specific rules.</p><p>Then, validation takes place.</p><p>For example, the date format is checked, mandatory fields are examined, and identification number formatting rules are applied.</p><p>One important distinction: Successfully recognizing text does not prove that the information is genuine or that the document is valid. Document verification and identity verification are separate security processes.</p><h4>7. The Result: From an Image to Structured Data</h4><p>At the end of the pipeline, the application can transform the photograph into a structured data object.</p><p>For example:</p><pre>{<br>  &quot;first_name&quot;: &quot;KEMAL&quot;,<br>  &quot;last_name&quot;: &quot;AYDIN&quot;,<br>  &quot;birth_date&quot;: &quot;1923-10-29&quot;,<br>  &quot;document_type&quot;: &quot;national_id&quot;,<br>  &quot;ocr_confidence&quot;: 0.98<br>}</pre><p><em>Note: This is entirely fictional sample data. An OCR confidence score does not establish the authenticity or validity of an identity document.</em></p><p>As we can see, a process that starts with capturing a photograph goes through image enhancement, geometric transformation, text detection, character recognition, and data validation before becoming meaningful information.</p><p>This is where the real power of image processing in software development becomes visible!</p><p><strong>A final note:</strong> Identity documents contain sensitive personal information. Applications processing such documents must consider user consent, data minimization, secure storage, access control, and applicable privacy regulations.</p><p>Image processing may initially look like a collection of complicated mathematical formulas. However, once we understand the fundamentals, it becomes a fascinating field full of opportunities to experiment and create.</p><p>In this article, we explored grayscale conversion, contrast stretching, histogram equalization, filtering, thresholding, and edge detection.</p><p>I believe the best way to learn image processing is not simply to read about algorithms, but to apply them to real images and observe what happens.</p><p>After all, sometimes changing a single pixel can make a big difference!</p><p><strong>Which algorithm would you like to experiment with first? See you in the next experiment!</strong></p><p>Finally, I’ve set up a GitHub page (<a href="https://kemalaydin.github.io/Pixel-Playground/">https://kemalaydin.github.io/Pixel-Playground/</a>) so you can try out what I’ve explained in this blog post using your own images.<br>The images aren’t stored on any server; they’re accessed via your browser.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b63f4766a17" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/pixels-have-stories-the-hidden-world-of-image-processing-6b63f4766a17">Pixels Have Stories: The Hidden World of Image Processing</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The AI Revolution in Laravel: Modern Backend Architecture with AI SDK, Boost, and MCP]]></title>
            <link>https://levelup.gitconnected.com/the-ai-revolution-in-laravel-modern-backend-architecture-with-ai-sdk-boost-and-mcp-022563c17068?source=rss-90d9cb5e14f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/022563c17068</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[laravel-ai-sdk]]></category>
            <category><![CDATA[ai-laravel]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Kemal Aydın]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 14:36:06 GMT</pubDate>
            <atom:updated>2026-10-09T14:36:06.303Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XBD175wB2qE7XoRrBkKTQw.png" /></figure><p>For years, when backend engineers discussed AI integration, the conversation revolved around Python microservices, LangChain wrappers, or fragile HTTP clients trying to parse non-deterministic text responses. With its official suite of AI-native tools, the Laravel ecosystem brings its signature focus on developer experience to production-grade artificial intelligence.</p><p>Building AI features is no longer just about dispatching prompts to raw LLM endpoints. It is about orchestrating <strong>agents that interact with relational databases</strong>, serving application logic to external clients via the <strong>Model Context Protocol (MCP)</strong>, and supercharging coding assistants with <strong>deep project context</strong>.</p><p>This article breaks down Laravel’s AI trifecta — <strong>Laravel AI SDK</strong>, <strong>Laravel Boost</strong>, and <strong>Laravel MCP</strong> — with architectural patterns and hands-on code examples.</p><h3>1. Laravel AI SDK (laravel/ai): Embedding Autonomous Agents into Your Application</h3><p>Integrating LLMs directly into an application often introduces production headaches: vendor rate limits, unexpected downtime, non-deterministic formatting, and synchronous bottlenecks. The laravel/ai SDK solves these hurdles natively using Laravel&#39;s battle-tested infrastructure (Queues, Events, Cache).</p><h3>Key Architectural Capabilities</h3><ul><li><strong>Resilient Failover:</strong> If your primary provider (e.g., Anthropic) encounters downtime or rate limits, traffic automatically and seamlessly redirects to a secondary provider (e.g., OpenAI or Gemini).</li><li><strong>Strict Structured Outputs:</strong> Bypasses unstructured strings by enforcing typed schemas that align directly with Laravel’s validation and Data Transfer Object (DTO) patterns.</li><li><strong>Queue-Native Execution:</strong> Transform heavy model inferences into asynchronous jobs simply by chaining queue().</li></ul><h3>Practical Example: A Customer Support Agent with Tool Calling</h3><p>Here is how to build an agent that can query order statuses directly from the database and handle returns.</p><h4>Step 1: Define the Tool</h4><pre>namespace App\Ai\Tools;<br><br>use App\Models\Order;<br>use Laravel\Ai\Contracts\Tool;<br><br>class GetOrderStatusTool implements Tool<br>{<br>    public function name(): string<br>    {<br>        return &#39;get_order_status&#39;;<br>    }<br><br>    public function description(): string<br>    {<br>        return &#39;Retrieves real-time shipping and delivery status using the customer order reference code.&#39;;<br>    }<br><br>    public function parameters(): array<br>    {<br>        return [<br>            &#39;order_number&#39; =&gt; [<br>                &#39;type&#39; =&gt; &#39;string&#39;,<br>                &#39;description&#39; =&gt; &#39;The order reference code to query (e.g., ORD-10928)&#39;,<br>                &#39;required&#39; =&gt; true,<br>            ],<br>        ];<br>    }<br><br>    public function execute(array $arguments): array<br>    {<br>        $order = Order::where(&#39;reference_code&#39;, $arguments[&#39;order_number&#39;])-&gt;first();<br><br>        if (! $order) {<br>            return [&#39;status&#39; =&gt; &#39;not_found&#39;, &#39;message&#39; =&gt; &#39;Order not found in the system.&#39;];<br>        }<br><br>        return [<br>            &#39;status&#39; =&gt; $order-&gt;status,<br>            &#39;tracking_url&#39; =&gt; $order-&gt;tracking_url,<br>            &#39;estimated_delivery&#39; =&gt; $order-&gt;estimated_delivery_at?-&gt;toIso8601String(),<br>        ];<br>    }<br>}</pre><h4>Step 2: Define the Agent and Failover Strategy</h4><pre>namespace App\Ai\Agents;<br><br>use App\Ai\Tools\GetOrderStatusTool;<br>use Laravel\Ai\Agent;<br>use Laravel\Ai\Concerns\HasStructuredOutput;<br><br>class CustomerSupportAgent extends Agent<br>{<br>    use HasStructuredOutput;<br><br>    public function instructions(): string<br>    {<br>        return &lt;&lt;&lt;PROMPT<br>        You are a helpful and polite customer support assistant.<br>        Always execute the designated tools when a user asks about order status.<br>        If an order has shipped, provide the tracking URL.<br>        PROMPT;<br>    }<br><br>    public function tools(): array<br>    {<br>        return [<br>            new GetOrderStatusTool(),<br>        ];<br>    }<br><br>    public function provider(): string<br>    {<br>        return &#39;anthropic:claude-3-5-sonnet-latest&#39;;<br>    }<br><br>    public function fallbackProviders(): array<br>    {<br>        return [<br>            &#39;openai:gpt-4o&#39;,<br>        ];<br>    }<br>}</pre><h4>Step 3: Handle Requests in the Controller</h4><pre>namespace App\Http\Controllers;<br><br>use App\Ai\Agents\CustomerSupportAgent;<br>use Illuminate\Http\JsonResponse;<br>use Illuminate\Http\Request;<br><br>class SupportController extends Controller<br>{<br>    public function ask(Request $request, CustomerSupportAgent $agent): JsonResponse<br>    {<br>        $request-&gt;validate([&#39;message&#39; =&gt; &#39;required|string|max:1000&#39;]);<br><br>        $response = $agent-&gt;ask($request-&gt;input(&#39;message&#39;));<br><br>        return response()-&gt;json([<br>            &#39;reply&#39; =&gt; $response-&gt;text(),<br>            &#39;used_tools&#39; =&gt; $response-&gt;toolCalls(),<br>        ]);<br>    }<br>}</pre><h3>2. Laravel Boost (laravel/boost): Project-Aware AI Development</h3><p>Modern AI coding agents (Cursor, Claude Code, GitHub Copilot) accelerate development, but frequently stumble due to two key blind spots:</p><ol><li><strong>Outdated Training Cutoffs:</strong> Models often generate legacy syntax from older Laravel versions instead of using modern conventions.</li><li><strong>Missing Schema Context:</strong> The AI guesses model relations, table columns, and casting attributes based purely on file names.</li></ol><p>laravel/boost spins up an internal <strong>Model Context Protocol (MCP)</strong> server on your machine, equipping your AI assistant with direct visibility into your database and terminal:</p><pre>composer require laravel/boost --dev<br>php artisan boost:install</pre><h3>What It Delivers</h3><ul><li><strong>Live Schema Inspection:</strong> When writing Eloquent queries, the model queries php artisan model:show under the hood, matching database types and columns with zero guesswork.</li><li><strong>Version-Aware Documentation:</strong> Boost injects vectorized documentation matching the exact package versions in your composer.lock, eliminating deprecated patterns.</li><li><strong>Log Diagnostics:</strong> When an exception occurs, your assistant inspects storage/logs/laravel.log directly to pinpoint the exact stack trace.</li></ul><h3>3. Laravel MCP (laravel/mcp): Exposing Application Services to External Agents</h3><p>The Model Context Protocol (MCP) is the open standard bridging language models with operational data sources. With laravel/mcp, your application becomes an authenticated MCP server capable of exposing business logic as callable <strong>Tools</strong>, <strong>Resources</strong>, and <strong>Prompts</strong> to external clients (such as Claude Desktop or autonomous workflows).</p><h3>Practical Scenario: Providing Account Balances to External AI Workflows</h3><p>Here is how you expose an internal customer query tool as an MCP service:</p><pre>namespace App\Mcp\Tools;<br><br>use App\Models\User;<br>use Laravel\Mcp\Server\Tool;<br>use Laravel\Mcp\Server\Attributes\Description;<br><br>#[Description(&#39;Retrieves the current account balance and active subscription tier for a given user email.&#39;)]<br>class CheckUserBalanceTool extends Tool<br>{<br>    public function handle(string $email): array<br>    {<br>        $user = User::where(&#39;email&#39;, $email)-&gt;first();<br><br>        if (! $user) {<br>            return [&#39;error&#39; =&gt; &#39;User not found.&#39;];<br>        }<br><br>        return [<br>            &#39;name&#39; =&gt; $user-&gt;name,<br>            &#39;balance&#39; =&gt; $user-&gt;wallet?-&gt;balance ?? 0,<br>            &#39;currency&#39; =&gt; &#39;EUR&#39;,<br>            &#39;plan&#39; =&gt; $user-&gt;subscription?-&gt;plan_name ?? &#39;Free&#39;,<br>        ];<br>    }<br>}</pre><p>Once registered in your MCP routes or configuration, any authenticated external AI client can process requests like:</p><blockquote>“Check the balance for kemal@example.com and alert the account manager if it is below 50 EUR.”</blockquote><p>The AI parses the intent, validates the parameters, and invokes your Laravel MCP tool securely without requiring bespoke REST endpoints.</p><p>Rather than treating AI as an isolated, third-party concern, Laravel integrates machine intelligence into the core framework primitives — queues, artisan commands, Eloquent models, and service providers — turning artificial intelligence into a first-class citizen of modern PHP backend systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=022563c17068" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-ai-revolution-in-laravel-modern-backend-architecture-with-ai-sdk-boost-and-mcp-022563c17068">The AI Revolution in Laravel: Modern Backend Architecture with AI SDK, Boost, and MCP</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel Dünyasında Yapay Zeka Devrimi]]></title>
            <link>https://aydinkml.medium.com/laravel-d%C3%BCnyas%C4%B1nda-yapay-zeka-devrimi-54cbf1884bfc?source=rss-90d9cb5e14f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/54cbf1884bfc</guid>
            <category><![CDATA[laravel-ai-sdk]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-laravel]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Kemal Aydın]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 19:59:18 GMT</pubDate>
            <atom:updated>2026-10-07T20:12:28.390Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XBD175wB2qE7XoRrBkKTQw.png" /></figure><p>Son birkaç yıldır yapay zeka dendiğinde backend geliştiricilerinin aklına çoğunlukla Python, LangChain veya ham HTTP çağrılarıyla yönetilmeye çalışılan kırılgan API entegrasyonları geliyordu. Ancak Laravel ekosistemi, karmaşık altyapı problemlerini zarif yaklaşımıyla çözme vizyonunu bir kez daha ortaya koydu ve resmi yapay zeka araç setini tanıttı.</p><p>Artık mesele yalnızca bir LLM endpoint’ine prompt göndermek değil; modelleri veritabanımızla konuşturan ajanlar tasarlamak, harici AI istemcilerine güvenli protokollerle (MCP) servis sunmak ve geliştirme yaparken kullandığımız AI asistanlarını projemizin bağlamıyla beslemek.</p><p>Bu yazıda, Laravel ekosisteminin yapay zeka üçlüsünü (<strong>Laravel AI SDK</strong>, <strong>Laravel Boost</strong> ve <strong>Laravel MCP</strong>) mimari detayları ve pratik kod örnekleriyle ele alacağız.</p><h3><strong>1. Laravel AI SDK (laravel/ai): Uygulamanıza Ajan Yeteneği Kazandırmak</strong></h3><p>Geleneksel entegrasyonlarda en büyük problem, LLM yanıtlarının belirliyici olmaması, model sağlayıcılarının kota veya kesinti problemleri ve asenkron işleme zorluğuydu. <a href="https://github.com/laravel/ai">laravel/ai</a>, bu problemleri Laravel&#39;in çekirdek yapılarıyla (Queue, Events, Cache) doğal şekilde çözer.</p><h4>Temel Özellikler</h4><ul><li><strong>Failover Mimarisi:</strong> OpenAI çökerse veya rate limit’e takılırsa, trafik otomatik ve şeffaf olarak Claude veya Gemini’a yönlendirilir.</li><li><strong>Katı Şema Doğrulama (Structured Output):</strong> Serbest metin yerine Laravel’in FormRequest veya DTO mantığıyla birebir örtüşen tipli yanıtlar üretir.</li><li><strong>Kuyruk Entegrasyonu:</strong> LLM çağrıları tek bir queue() zinciriyle asenkron job&#39;lara dönüştürülebilir.</li></ul><p>Müşterinin sipariş durumunu sorgulayan ve gerekirse iade süreci başlatan bir ajan kurgulayalım.</p><h4>Adım 1: Ajanın Kullanacağı Aracı Tanımlama</h4><pre>namespace App\Ai\Tools;<br><br>use App\Models\Order;<br>use Laravel\Ai\Contracts\Tool;<br><br>class GetOrderStatusTool implements Tool<br>{<br>    public function name(): string<br>    {<br>        return &#39;get_order_status&#39;;<br>    }<br><br>    public function description(): string<br>    {<br>        return &#39;Müşterinin sipariş numarasını alarak güncel kargo ve teslimat durumunu sorgular.&#39;;<br>    }<br><br>    public function parameters(): array<br>    {<br>        return [<br>            &#39;order_number&#39; =&gt; [<br>                &#39;type&#39; =&gt; &#39;string&#39;,<br>                &#39;description&#39; =&gt; &#39;Sorgulanacak sipariş referans kodu (ör: ORD-10928)&#39;,<br>                &#39;required&#39; =&gt; true,<br>            ],<br>        ];<br>    }<br><br>    public function execute(array $arguments): array<br>    {<br>        $order = Order::where(&#39;reference_code&#39;, $arguments[&#39;order_number&#39;])-&gt;first();<br><br>        if (! $order) {<br>            return [&#39;status&#39; =&gt; &#39;not_found&#39;, &#39;message&#39; =&gt; &#39;Sipariş sistemde bulunamadı.&#39;];<br>        }<br><br>        return [<br>            &#39;status&#39; =&gt; $order-&gt;status,<br>            &#39;tracking_url&#39; =&gt; $order-&gt;tracking_url,<br>            &#39;estimated_delivery&#39; =&gt; $order-&gt;estimated_delivery_at?-&gt;toIso8601String(),<br>        ];<br>    }<br>}</pre><h4>Adım 2: Ajan Tanımı ve Failover Yapılandırması</h4><pre>namespace App\Ai\Agents;<br><br>use App\Ai\Tools\GetOrderStatusTool;<br>use Laravel\Ai\Agent;<br>use Laravel\Ai\Concerns\HasStructuredOutput;<br><br>class CustomerSupportAgent extends Agent<br>{<br>    use HasStructuredOutput;<br><br>    public function instructions(): string<br>    {<br>        return &lt;&lt;&lt;PROMPT<br>        Sen nazik ve çözüm odaklı bir müşteri hizmetleri asistanısın. <br>        Kullanıcı sipariş sorduğunda mutlaka ilgili aracı çalıştır. <br>        Eğer sipariş kargoda ise kargo takip bağlantısını paylaş.<br>        PROMPT;<br>    }<br><br>    public function tools(): array<br>    {<br>        return [<br>            new GetOrderStatusTool(),<br>        ];<br>    }<br><br>    public function provider(): string<br>    {<br>        return &#39;anthropic:claude-3-5-sonnet-latest&#39;;<br>    }<br><br>    // KEsinti olursa çalışacak olan<br>    public function fallbackProviders(): array<br>    {<br>        return [<br>            &#39;openai:gpt-4o&#39;,<br>        ];<br>    }<br>}</pre><h4>Adım 3: Controller Üzerinde Kuyruklama ve Yanıt Alma</h4><pre>namespace App\Http\Controllers;<br><br>use App\Ai\Agents\CustomerSupportAgent;<br>use Illuminate\Http\JsonResponse;<br>use Illuminate\Http\Request;<br><br>class SupportController extends Controller<br>{<br>    public function ask(Request $request, CustomerSupportAgent $agent): JsonResponse<br>    {<br>        $request-&gt;validate([&#39;message&#39; =&gt; &#39;required|string|max:1000&#39;]);<br><br>        // Arka plan kuyruğuna eklenebilir veya senkron çalıştırılabilir:<br>        $response = $agent-&gt;ask($request-&gt;input(&#39;message&#39;));<br><br>        return response()-&gt;json([<br>            &#39;reply&#39; =&gt; $response-&gt;text(),<br>            &#39;used_tools&#39; =&gt; $response-&gt;toolCalls(),<br>        ]);<br>    }<br>}</pre><h3>2. Laravel Boost (laravel/boost): Geliştirici Ortamını Projeye Uyumlu Kılmak</h3><p>LLM destekli editörler (Cursor, Claude Code, GitHub Copilot) harikadır, ancak iki büyük kusurları vardır:</p><ol><li><strong>Model Eğitimi Eskimesi:</strong> Model, projenizdeki Laravel 11/12 yenilikleri yerine Laravel 8 veya 9 kalıplarıyla kod önerebilir.</li><li><strong>Kör Noktalar:</strong> Editör, routes/api.php dosyanızı ya da veritabanınızdaki migration ilişkilerini varsayımlarla çözmeye çalışır.</li></ol><p><a href="https://github.com/laravel/boost">laravel/boost</a>, projenize bir <strong>Model Context Protocol (MCP)</strong> sunucusu kurarak yapay zeka asistanınıza terminal ve veritabanı erişim pencereleri açar:</p><pre>composer require laravel/boost --dev<br>php artisan boost:install</pre><h3>Ne Sağlar?</h3><ul><li><strong>Gerçek Şema :</strong> Model kod yazarken php artisan model:show veya şema tablolarını arka planda sorgulayarak sütun isimlerini ve casting kurallarını sıfır hatayla tahmin eder.</li><li><strong>Versiyona Özel Dokümantasyon:</strong> Projenizde yüklü Composer paketlerinin sürümlerine karşılık gelen vektörel Laravel dokümanlarını bağlama ekler; deprecated syntax kullanımını ortadan kaldırır.</li><li><strong>Tinker ve Log Araçları:</strong> Hata aldığınızda asistan, laravel.log dosyasını doğrudan inceleyip hatanın kaynağını pinpoint tespit edebilir.</li></ul><h3>3. Laravel MCP (laravel/mcp): Uygulamanızı Dış Dünyadaki AI Ajanlarına Açmak</h3><p>Model Context Protocol (MCP), LLM istemcileri ile veri kaynakları arasındaki iletişimi standartlaştıran açık bir protokoldür. <a href="https://github.com/laravel/mcp">laravel/mcp</a> paketi sayesinde projeniz, harici AI ajanlarının (örneğin kurumsal Claude masaüstü uygulaması veya özel geliştirilmiş AI ajanları) tüketebileceği standart bir sunucu haline gelir.</p><p>Projemizdeki bir veritabanı sorgusunu MCP kaynağı ve aracı olarak dışarı sunalım:</p><pre>namespace App\Mcp\Tools;<br><br>use App\Models\User;<br>use Laravel\Mcp\Server\Tool;<br>use Laravel\Mcp\Server\Attributes\Description;<br><br>#[Description(&#39;Verilen e-posta adresine ait kullanıcının güncel bakiye ve üyelik planı bilgisini getirir.&#39;)]<br>class CheckUserBalanceTool extends Tool<br>{<br>    public function handle(string $email): array<br>    {<br>        $user = User::where(&#39;email&#39;, $email)-&gt;first();<br><br>        if (! $user) {<br>            return [&#39;error&#39; =&gt; &#39;Kullanıcı bulunamadı.&#39;];<br>        }<br><br>        return [<br>            &#39;name&#39; =&gt; $user-&gt;name,<br>            &#39;balance&#39; =&gt; $user-&gt;wallet?-&gt;balance ?? 0,<br>            &#39;currency&#39; =&gt; &#39;TRY&#39;,<br>            &#39;plan&#39; =&gt; $user-&gt;subscription?-&gt;plan_name ?? &#39;Free&#39;,<br>        ];<br>    }<br>}</pre><p>Bu araç routes/ai.php veya MCP konfigürasyonunda tanımlandığında, yetkilendirilmiş herhangi bir MCP istemcisi (Desktop Claude veya bağımsız bir bot) API endpoint&#39;leri için özel kod yazmaya gerek duymadan doğrudan şu sorguyu yapabilir:</p><blockquote>“kemal@example.com kullanıcısının bakiyesini kontrol et ve yetersizse bildirim tetikle.”</blockquote><p>İstemci aracı keşfeder, parametreleri validate eder, Laravel uygulamamız güvenli şekilde işlemi çalıştırır ve sonucu ajana döner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*digwtB_-72KIIjWjDp3ntA.png" /></figure><p>Laravel, yapay zekayı harici bir teknoloji yığını gibi konumlandırmak yerine; kuyrukları, servis sağlayıcıları, veritabanı katmanı ve artisan komutlarıyla doğrudan <strong>çatının yerel bir kullanıcısı</strong> haline getiriyor.</p><p>Bir başka yazıda görüşmek üzere 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54cbf1884bfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bribing the Bouncer: What the Hell is a Preflight Request?]]></title>
            <link>https://levelup.gitconnected.com/bribing-the-bouncer-what-the-hell-is-a-preflight-request-afd3ac96b9f4?source=rss-90d9cb5e14f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/afd3ac96b9f4</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[cors]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[preflight-request]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Kemal Aydın]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 18:23:44 GMT</pubDate>
            <atom:updated>2026-09-21T18:23:44.039Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3ZJO--nNBQDOe72NDbu0w.png" /></figure><h3>Bribing the Bouncer: What the Hell is a Preflight Request?</h3><p>Every web developer remembers their rite of passage. You spin up a backend service, write a shiny client-side script, fire off a simple fetch() or axios.post() call, and lean back to admire your craftsmanship.</p><p>Then your browser console explodes in vibrant, radioactive red:</p><blockquote>“Access to fetch at ‘<a href="https://www.google.com/search?q=https://api.backend.com&amp;utm_source=gemini">https://api.backend.com</a>&#39; from origin ‘<a href="https://www.google.com/url?sa=E&amp;source=gmail&amp;q=https://my-awesome-app.com">https://this-is-my-app.com</a>&#39; has been blocked by CORS policy: Response to preflight request doesn’t pass access control check…</blockquote><p>You pop open the DevTools Network tab expecting to troubleshoot your payload, only to find an uninvited guest masquerading as an HTTP method: OPTIONS.</p><p>You never wrote an OPTIONS request. Nobody writes OPTIONS requests on purpose. So who invited it, and why is it sabotaging your sprint?</p><p>Welcome to the browser’s favorite surveillance mechanism: <strong>The Preflight Request</strong>.</p><h3>The VIP Lounge Analogy</h3><p>Think of the web ecosystem as a slightly pretentious, high-end night club:</p><ul><li><strong>Your Client Code:</strong> A wide-eyed clubber eager to get in and dance with the database.</li><li><strong>The API Server:</strong> The exclusive venue with an intimidating dress code.</li><li><strong>The Browser:</strong> Your ridiculously overprotective parent who drove you to the club and refuses to let you out of the car until they speak with the manager.</li></ul><p>If you roll up wearing plain clothes — like submitting an old-school HTML form or firing a basic GET query—the browser shrugs and lets you go. The W3C calls this a <strong>Simple Request</strong>. The risk is minimal, and the server knows how to handle common foot traffic.</p><p>Then modern single-page apps happened. Now you walk up to the door and tell your browser:</p><ol><li><em>“I’m carrying a fancy leather briefcase.”</em> (Content-Type: application/json)</li><li><em>“I’ve got an exclusive backstage pass pinned to my lapel.”</em> (Authorization: Bearer &lt;token&gt;)</li><li><em>“Also, I plan on ripping out a VIP booth and putting a new one in.”</em> (PUT, PATCH, or DELETE)</li></ol><p>At that point, the browser grabs you by the collar: <strong>“Hold your horses, rockstar. You can’t just storm in dressed like an enterprise payload. Let me check with the bouncer first to see if they tolerate your existence.”</strong></p><p>That recon scout dispatched by the browser is the <strong>Preflight Request</strong>.</p><h3>The Walkie-Talkie Wiretap</h3><p>If you listen in on the network traffic right before your code actually executes, the negotiation looks remarkably bureaucratic.</p><p><strong>The Browser asks permission via </strong>OPTIONS<strong>:</strong></p><p>HTTP</p><pre>OPTIONS /api/v1/checkout HTTP/1.1<br>Host: api.backend.com<br>Origin: https://this-is-my-app.com<br>Access-Control-Request-Method: POST<br>Access-Control-Request-Headers: Content-Type, Authorization</pre><p><em>Subtext:</em> “Hey bouncer. Kid from https://this-is-my-app.com wants to send a POST. They want to bring JSON and an Authorization header. Are we cool, or are you calling security?&quot;</p><p>If the backend engineer configured CORS properly, the server nods and waves the green flag:</p><p><strong>The Server responds (usually with a </strong>204 No Content<strong> or </strong>200 OK<strong>):</strong></p><p>HTTP</p><pre>HTTP/1.1 204 No Content<br>Access-Control-Allow-Origin: https://this-is-my-app.com<br>Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE<br>Access-Control-Allow-Headers: Content-Type, Authorization<br>Access-Control-Max-Age: 86400</pre><p><em>Subtext:</em> “Yeah, we know that domain. They can run a POST, and those headers are fine. Also, write this down: don&#39;t ask me again for the next 24 hours (86400 seconds).&quot;</p><p>Once the browser hears that, it finally lets go of your sleeve and fires your actual, intended POST request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*vsbEqZOHUnuxBi-az7xB3A.jpeg" /></figure><h3>Two Landmines That Break Prod</h3><p>Preflight isn’t malicious; it exists to shield legacy endpoints from unauthorized cross-origin mutations. Still, it trips up even experienced teams in two hilarious ways:</p><h4>1. The Overzealous JWT Guard</h4><p>You build a global authentication middleware that intercepts every incoming request to verify bearer tokens.</p><p>Here’s the catch: <strong>Preflight </strong>OPTIONS<strong> requests do not carry user credentials.</strong></p><p>Your server promptly smacks the OPTIONS call with a 401 Unauthorized. The browser concludes the bouncer threw a punch, so it kills your real request before it ever leaves the station.</p><p><em>Fix:</em> Exempt OPTIONS methods from your auth guards. Never demand an ID from the messenger asking where the door is.</p><h4>2. Network Latency Ping-Pong</h4><p>If you trigger a preflight check before <em>every single API mutation</em>, you double your round-trip time. On spotty cellular connections, your slick single-page app suddenly feels like dial-up.</p><p><em>Fix:</em> Set a healthy Access-Control-Max-Age header on preflight responses. Tell the browser to cache the verdict so it doesn&#39;t run back to the bouncer every two seconds.</p><p>Preflight requests aren’t a bug in your code; they are the browser running security clearance behind your back. The next time the console paints your screen red, don’t scream at your framework — just check the OPTIONS exchange to see which header offended the bouncer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afd3ac96b9f4" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/bribing-the-bouncer-what-the-hell-is-a-preflight-request-afd3ac96b9f4">Bribing the Bouncer: What the Hell is a Preflight Request?</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kapıdaki Korumayı Aşma Sanatı: Preflight Request Nedir, Tarayıcı Bizden Ne İster?]]></title>
            <link>https://aydinkml.medium.com/kap%C4%B1daki-korumay%C4%B1-a%C5%9Fma-sanat%C4%B1-preflight-request-nedir-taray%C4%B1c%C4%B1-bizden-ne-i%CC%87ster-5785a546e226?source=rss-90d9cb5e14f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5785a546e226</guid>
            <category><![CDATA[cors]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[preflight-request]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Kemal Aydın]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 07:48:54 GMT</pubDate>
            <atom:updated>2026-09-21T07:55:34.208Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3ZJO--nNBQDOe72NDbu0w.png" /></figure><p>Web geliştirmeye yeni başlayan herkesin mutlaka yaşadığı o kutsal bir vaftiz anı vardır: Kodunu yazarsın, backend endpoint’ini hazırlarsın, fetch() veya axios ile isteği ateşlersin... Ve tarayıcı konsolunda o meşhur, kıpkırmızı, insanın içini buz kestiren hata belirir:</p><blockquote>“Access to fetch at ‘<a href="https://www.google.com/search?q=https://api.backend.com&amp;utm_source=gemini">https://api.backend.com</a>&#39; from origin ‘<a href="https://my-app.com/?utm_source=gemini">https://this-is-my-my-app.com</a>&#39; has been blocked by CORS policy…”</blockquote><p>Hemen arkasından Network sekmesini açarsın ve hayatında yazmadığın bir HTTP metodunun orada durduğunu görürsün: <strong>OPTIONS</strong>.</p><p>“Yahu ben POST attım, bu OPTIONS nereden çıktı? Kim çağırdı bunu?&quot; diyorsan tebrikler; tarayıcının güvenlik paranoyasının en naif ürünü olan <strong>Preflight Request (Ön Uçuş İsteği)</strong> ile tanıştın.</p><p>Gelin bu mevzuyu, gereksiz akademik terimlerin arkasına saklanmadan, hayatın içinden bir analojiyle masaya yatıralım.</p><h3>Gece Kulübü Kapısındaki Takım Elbiseli Abi</h3><p>Olayı kafada canlandırmak için klasik bir senaryo kuralım:</p><ul><li><strong>Tarayıcı (Browser):</strong> Aşırı korumacı, kuralcı ve her şeyden nemkapan bir menajer.</li><li><strong>Backend API:</strong> Girişte kadın — erkek sayısı eşitliğini kontrol eden ve erkek sayısı fazla ise kabul etmeyen (bkz. <a href="https://x.com/KelimeKoken/status/1268680372897841152">damsız</a>) , içeride kimin ne yaptığını çok sıkı denetleyen lüks bir gece kulübü.</li><li><strong>Frontend Kodun:</strong> Kulübe girip eğlenmek (yani veri alıp/vermek) isteyen heyecanlı genç.</li></ul><p>Normal şartlarda elinde standart bir dilekçeyle gidersen (klasik bir form postu ya da dümdüz bir GET isteği), tarayıcı seni çok darlamaz. &quot;Tamam geç&quot; der. Buna W3C amcaları <strong>Simple Request (Basit İstek)</strong> diyor.</p><p>Ama sen kalkıp dedin ki:</p><ol><li><em>“Ben içeri öyle dümdüz girmem, elimde şık bir çanta olacak!”</em> (Yani: Content-Type: application/json)</li><li><em>“Yakama da özel VIP rozetimi takarım!”</em> (Yani: Authorization: Bearer &lt;token&gt;)</li><li><em>“Hatta içeri girip içerideki bir masayı tamamen kaldırıp yenisini koyacağım!”</em> (Yani: PUT veya DELETE)</li></ol><p>İşte tam bu anda tarayıcı kolundan tutar ve der ki: <strong>“Dur bakalım şampiyon. Sen içeri böyle paldır küldür giremezsin. Önce ben bir gidip sorayım, bu kıyafetle seni içeri alıyorlar mı?”</strong></p><p>İşte tarayıcının önden gönderip kapıdaki güvenlikle fısıldaştığı o keşif görevine <strong>Preflight Request</strong> diyoruz. Kullandığı araç da OPTIONS metodudur.</p><h3>Perde Arkasındaki Telsiz Konuşması</h3><p>Ağ trafiğini dinlediğimizde dönen diyalog birebir şudur:</p><p><strong>Tarayıcı (OPTIONS isteği atar):</strong></p><pre>OPTIONS /api/v1/profile HTTP/1.1<br>Host: api.backend.com<br>Origin: https://this-is-my-app.com<br>Access-Control-Request-Method: POST<br>Access-Control-Request-Headers: Content-Type, Authorization</pre><p><em>Tercümesi:</em> “Selamlar usta. Bizim çocuk https://this-is-my-app.com adresinden geliyor. Birazdan bir POST atacak; yanında da application/json ile Authorization başlığı getirmek istiyor. Müsaadeniz var mı, kapıyı açar mısınız?&quot;</p><p>Eğer backend geliştiricisi işini düzgün yaptıysa ve CORS ayarlarını girdiyse, sunucu tebessümle yanıt verir:</p><p><strong>Sunucu (204 No Content veya 200 OK yanıtı döner):</strong></p><pre>HTTP/1.1 204 No Content<br>Access-Control-Allow-Origin: https://this-is-my-app.com<br>Access-Control-Allow-Methods: POST, GET, OPTIONS<br>Access-Control-Allow-Headers: Content-Type, Authorization<br>Access-Control-Max-Age: 86400</pre><p><em>Tercümesi:</em> “Selam. this-is-my-app.com tanıdık, gelsin. POST atabilir, o başlıklara da izin verdim. Hatta bu izni hafızana yaz, önümüzdeki 24 saat (86400 saniye) boyunca aynı şey için kapımı tekrar çalma.&quot;</p><p>İşte bu yeşil ışıktan sonra tarayıcı rahatlar, senin asıl kodunu serbest bırakır ve asıl POST isteği hedefine ulaşır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*vsbEqZOHUnuxBi-az7xB3A.jpeg" /></figure><h3>Geliştiricileri Delirten 2 Büyük Tuzak</h3><p>Preflight aslında can dostumuzdur, CSRF ve yetkisiz kaynak erişimlerine karşı arkamızı kollar. Ama onu tanımayan yazılımcıya saç baş yoldurur. En sık düşülen iki çukur şunlardır:</p><h4>1. “OPTIONS İsteğine de JWT Soran” Cefakar Backend’ci</h4><p>Global bir auth middleware yazmışsındır. Gelen her isteğin Authorization başlığındaki token’ı doğrulamaya çalışıyordur. Fakat minik bir detay vardır: <strong>Preflight istekleri (</strong><strong>OPTIONS) kimlik doğrulama verisi taşımaz.</strong> Backend pat diye 401 Unauthorized basar. Tarayıcı da bakar ki kapıdaki koruma &quot;Kimsin lan sen?&quot; diyor; senin asıl isteğini hiç göndermeden çöpe atar. <em>Çözüm:</em> OPTIONS isteklerini auth kontrolünden muaf tutun; korumanın kendi üstünü aramayın.</p><h4>2. Network Sekmesinde “Ping-Pong” Turnuvası (Gecikme Problemi)</h4><p>Her veri çekişinde önce OPTIONS, sonra asıl istek giderse ne olur? Kullanıcının hissettiği API latency&#39;si anında ikiye katlanır. Mobil internetteysen durum tam bir eziyettir. <em>Çözüm:</em> Sunucu yanıtına mutlaka Access-Control-Max-Age ekleyin. Tarayıcıya &quot;Bir kere sordun, öğrendin, bir zahmet bir saat boyunca aynı şeyi sorma&quot; deyin.</p><h3>Sözün Özü</h3><p>Preflight bir hata değildir; tarayıcının <em>“Önce tedbir, sonra tevekkül”</em> felsefesidir. Konsolda kırmızı CORS yazısı gördüğünüzde monitöre yumruk atmak yerine Network sekmesindeki OPTIONS isteğine bakın: Hangi header&#39;a izin verilmemiş, hangi origin ters köşe olmuş, hemen fısıldar.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5785a546e226" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Sunday League to El Clásico: How SQL Row Locking Can Crush Your Database]]></title>
            <link>https://medium.com/codetodeploy/from-sunday-league-to-el-cl%C3%A1sico-how-sql-row-locking-can-crush-your-database-ddbc83781ab7?source=rss-90d9cb5e14f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddbc83781ab7</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[code-refactoring]]></category>
            <category><![CDATA[sql-tips]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[sql-locking]]></category>
            <dc:creator><![CDATA[Kemal Aydın]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 08:43:45 GMT</pubDate>
            <atom:updated>2026-08-11T08:43:45.901Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3LtI-ejI8p0dHj2JJfj0w.png" /></figure><p>When building software, most of us rely heavily on a classic safety net: <strong>ACID principles and SQL transaction management.</strong> We tell ourselves, <em>“SQL will ensure data consistency, so we’re fine.”</em> And we aren’t wrong. However, under heavy traffic, the very mechanism designed to protect your data integrity can quickly turn into your system’s biggest bottleneck.</p><blockquote><em>💥 </em><strong><em>Master AI &amp; Tech Skills </em></strong><br> 💥 Crack Every Tech Interview with Confidence<br> 🔥 Up to <strong>70% OFF</strong> — Limited-Time Offer<br> <a href="https://www.educative.io/unlimited?aff=xkRD"><em>👉 </em><strong><em>Enroll Now &amp; Start Learning</em></strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITogvtC6mF2BUF35Qsd9pg.png" /></figure><p>Today, we’re going to talk about one of the most silent performance killers in relational databases: <strong>Row-Level Locking</strong> and the hidden contention it creates.</p><p>Let’s walk through this using a scenario we can all relate to (and perhaps have suffered from).</p><h3>Sunday League vs. Barcelona vs. Real Madrid</h3><p>Imagine we are building a ticketing platform. The core logic sounds completely straightforward: every time a ticket is purchased, we decrement the available stock count in our database.</p><p>Our typical SQL statement looks like this:</p><pre>UPDATE tickets <br>SET stock = stock - 1 <br>WHERE match_id = 42;</pre><p>Now, suppose we are selling tickets for a local Sunday league match — let’s call it <strong>Muddy Boots FC vs. Barnaby’s Barber Shop FC</strong>.</p><p>Congratulations! Your code runs flawlessly. Traffic is minimal; maybe 1 or 2 users attempt to buy a ticket per hour. The database locks the single row, decrements the count, releases the lock, and carries on. Nobody notices a thing.</p><p><strong>However, everything changes when El Clásico (Barcelona vs. Real Madrid) goes live.</strong></p><p>The stadium holds 62,000 fans. The moment sales open, your application gets hit with <strong>5,000 requests per second</strong>. At this exact moment, that simple stock = stock - 1 query transforms into an architectural nightmare.</p><h3>What’s Happening Under the Hood? (The Row Locking Nightmare)</h3><p>The second your database (PostgreSQL, MySQL, etc.) receives the UPDATE query, it enforces data consistency by effectively saying:</p><blockquote>“Hold on! I am updating this row right now. Nobody else can touch it until my transaction completes!”</blockquote><p>It acquires an <strong>Exclusive Lock</strong> on that specific row.</p><p>All 5,000 incoming requests per second are attempting to mutate <strong>THE EXACT SAME ROW</strong>.</p><p>What is the immediate outcome?</p><ol><li><strong>Transaction Lock Contention:</strong> Request #1 locks the row. The remaining 4,999 requests hold open database connections and freeze in line waiting for the lock to be released.</li><li><strong>Connection Pool Exhaustion:</strong> Your application’s connection pool fills up in milliseconds. Users browsing other parts of the platform start receiving 504 Gateway Timeout errors.</li><li><strong>CPU Spikes to 100%:</strong> The database server burns excessive CPU cycles managing lock overhead, context switching, and coordinating thousands of blocked threads.</li><li><strong>Deadlock Risks:</strong> If this UPDATE query is part of a larger transaction involving other tables (e.g., user balances, order history), transactions will start blocking each other in circular dependencies, throwing Deadlock exceptions.</li></ol><p>In short: Your database preserved data consistency, but <strong>your system crashed and nobody actually bought a ticket.</strong> 😅</p><h3>How Do We Solve This?</h3><p>The golden rule when mitigating row locking bottlenecks is: <strong>Never issue direct, high-concurrency SQL UPDATEs to hot rows.</strong></p><p>Here are the battle-tested architectural approaches to survive El Clásico:</p><h3>1. In-Memory Atomic Operations via Redis</h3><p>The most common approach is shifting real-time inventory management away from relational storage into an in-memory store like <strong>Redis</strong>.</p><ul><li>Because Redis operates on a single-threaded execution loop, atomic commands like DECRBY execute in microseconds without requiring explicit database locks.</li><li>When a user attempts to purchase a ticket, inventory is checked and decremented in Redis first.</li><li>If Redis confirms available stock, the request is published to a <strong>Message Queue (RabbitMQ, Kafka, etc.)</strong>, where worker services asynchronously persist the order via SQL INSERT statements.</li></ul><pre>[Request] ──► [Redis DECRBY] ──(Stock Available)──► [Message Queue] ──► [Async SQL Insert]</pre><h3>2. Stock Sharding</h3><p>If business constraints require staying strictly within SQL, you can drastically reduce lock contention using a technique called <strong>Stock Sharding</strong>.</p><p>Instead of keeping the total ticket count in a single row, divide it across multiple bucket rows (e.g., 10 rows):</p><pre>+---------------+--------------+-----------+<br>|   Bucket ID   |   Match ID   |   Stock   |<br>|---------------+--------------+-----------|<br>|        1      |       42     |    6200   |<br>|        2      |       42     |    6200   |<br>|        3      |       42     |    6200   |<br>|       ...     |       42     |    6200   |<br>|       10      |       42     |    6200   |<br>+---------------+--------------+-----------+</pre><p>When a purchase comes in, your application randomly selects a Bucket ID to update. Splitting 5,000 requests across 10 independent rows reduces lock contention on any single row by up to 90%.</p><h3>3. Optimistic Locking</h3><p>Instead of letting the database implicitly block other reads/writes (Pessimistic Locking), you introduce a version or timestamp field.</p><pre>UPDATE tickets <br>SET stock = stock - 1, version = version + 1 <br>WHERE match_id = 42 AND version = 3;</pre><p>When the first request updates the row, version increments to 4. Concurrent queries looking for version = 3 immediately fail without waiting for a lock. Your application tier can then gracefully handle the failed attempt or trigger an application-level retry mechanism.</p><h3>Wrapping Up</h3><p>Handling a local Sunday league game is easy; true software engineering is tested when El Clásico traffic hits your stack.</p><p>SQL row-level locking is a vital integrity feature, but under <strong>high concurrency</strong>, it quickly becomes your primary single point of congestion. Identifying hot rows early and decoupling state updates using in-memory queues, distributed locks, or sharding will ensure your system stays resilient — and let you sleep peacefully at night.</p><p>Happy coding! 🚀</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9QTaaaxboQP_gKSLedW_w.png" /></figure><p>👉 Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></p><p>👉 Follow us: <a href="https://www.linkedin.com/in/bhuwan-kc-583505319/?isSelfProfile=true"><strong>Linkedin</strong></a>| <a href="https://medium.com/codetodeploy"><strong>Medium</strong></a></p><p>👉 CodeToDeploy Tech Community is live on Discord — <a href="https://discord.gg/ZpwhHq6D"><strong>Join now!</strong></a></p><p><strong>Disclosure:</strong> This post includes affiliate and partnership links.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddbc83781ab7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codetodeploy/from-sunday-league-to-el-cl%C3%A1sico-how-sql-row-locking-can-crush-your-database-ddbc83781ab7">From Sunday League to El Clásico: How SQL Row Locking Can Crush Your Database</a> was originally published in <a href="https://medium.com/codetodeploy">CodeToDeploy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Row Locking Nasıl Sistemini Yerle Bir Eder?]]></title>
            <link>https://aydinkml.medium.com/sql-row-locking-nas%C4%B1l-sistemini-yerle-bir-eder-4a316f705f12?source=rss-90d9cb5e14f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a316f705f12</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[locking]]></category>
            <category><![CDATA[sql-lock]]></category>
            <category><![CDATA[sql-tips]]></category>
            <dc:creator><![CDATA[Kemal Aydın]]></dc:creator>
            <pubDate>Mon, 03 Aug 2026 19:50:58 GMT</pubDate>
            <atom:updated>2026-08-03T20:19:22.488Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3LtI-ejI8p0dHj2JJfj0w.png" /></figure><p>Yazılım geliştirirken çoğumuzun arkasına yaslanıp güvendiği o liman vardır: <strong>ACID prensipleri ve SQL transactional yapısı.</strong> “Aman veri tutarsızlığı olmasın, SQL halleder” deriz. Haklıyız da. Ancak bazen veritabanımızın bizi korumak için attığı o koruyucu adımlar, yüksek trafik altında birer prangaya dönüşebilir.</p><p>Bugün, veritabanlarının en sinsi performans canavarlarından birini konuşacağız: <strong>Row-Level Locking (Satır Seviyesinde Kilitleme)</strong> ve onun yarattığı o gizli darboğazlar.</p><p>Gelin bunu hepimizin anlayabileceği eğlenceli (ve biraz can yakıcı) bir örnekle inceleyelim.</p><p>Bir bilet satış platformu geliştirdiğimizi düşünelim. Mantık oldukça basit: Her bilet satıldığında veritabanındaki stok değerini 1 azaltıyoruz.</p><p>SQL tarafında yazdığımız o meşhur kod satırı:</p><pre>UPDATE tickets <br>SET stock = stock - 1 <br>WHERE match_id = 42;</pre><p>Eğer bu sistemde <a href="https://youtu.be/3twlsRGkCiQ?t=15"><strong>Eşkin Market Bayır Turbanspor — Aksay Elektrik Yeknaz Sanköyspor</strong></a> maçının biletleri satılıyorsa… Tebrikler! Kodunuz mükemmel çalışır. Çünkü maça ilgi azdır, saatte belki 1–2 kişi bilet almaya çalışır. Veritabanı o tek satırı kilitler, stoğu düşer, kilidi açar ve hayatına devam eder. Kimse hiçbir şey hissetmez.</p><blockquote><strong>Fakat sahneye Barcelona — Real Madrid maçı çıktığında işler değişir.</strong></blockquote><p>Stadyum 62.000 kişilik. Biletler satışa açıldığı an saniyede <strong>5.000 talep</strong> sisteminize hücum ediyor. İşte tam bu noktada stock = stock - 1 sorgusu sisteminizi bir yangın yerine çevirmeye başlar.</p><h3>Arka Planda Neler Oluyor? (Row Locking Kabusu)</h3><p>Siz UPDATE sorgusunu attığınız an relational veritabanınız (PostgreSQL, MySQL vs.) veri bütünlüğünü korumak için şunu söyler:</p><blockquote>“Durun! Bu satırı şu an ben güncelliyorum. İşlemim (transaction) bitene kadar kimse bu satıra dokunamaz!”</blockquote><p>Ve o tek satıra <strong>Exclusive Lock</strong> (Özel Kilit) koyar.</p><p>Saniyede gelen 5.000 isteğin hepsi <strong>AYNI TEK SATIRI</strong> güncellemeye çalışmaktadır.</p><p>Sonuç mu?</p><ol><li><strong>Transaction Lock Contention (Kilit Rekabeti):</strong> İlk istek satırı kilitler. Kalan 4.999 istek veritabanı bağlantısını (connection) açık tutarak kuyrukta beklemeye başlar.</li><li><strong>Connection Pool’un Tükenmesi:</strong> Veritabanı bağlantı havuzunuz (Connection Pool) saniyeler içinde dolar. Bilet almaya çalışan kullanıcılar bir yana, sitede gezinen kullanıcılar bile 504 Gateway Timeout almaya başlar.</li><li><strong>CPU Tavan Yapar:</strong> Veritabanı sürekli kilit yönetimi ve bekleme durumundaki thread’leri koordine etmeye çalıştığı için CPU %100&#39;e vurur.</li><li><strong>Deadlock Riski:</strong> Eğer bu UPDATE işlemi başka tablolarla (örneğin kullanıcı bakiyesi, sipariş geçmişi) aynı transaction içindeyse, işlemler birbirini kilitler ve sistem Deadlock hataları fırlatmaya başlar.</li></ol><p>Yani kısacası: Veritabanınız veri tutarlılığını korumuştur ama <strong>sistem çöktüğü için kimse bilet alamamıştır.</strong> 😅</p><h3>Peki Bu Derdi Nasıl Çözeriz?</h3><p>Row locking sorununu çözmenin temel kuralı şudur: <strong>Yüksek trafikli satırları (Hot Rows) doğrudan ve eşzamanlı SQL UPDATE atmayı bırakın.</strong></p><p>İşte El Clásico maçını kazandıracak çözüm yaklaşımları:</p><h3>1. Redis ile Stok Yönetimi (In-Memory Atomic Operations)</h3><p>En yaygın ve etkili yöntem stok yönetimini ilişkisel veritabanından alıp <strong>Redis</strong> gibi bellekte çalışan bir yapıya taşımaktır.</p><ul><li>Redis tek thread (single-threaded) çalıştığı için DECRBY gibi atomic işlemleri kilit mekanizmasına ihtiyaç duymadan inanılmaz hızlı (microsecond seviyesinde) yapar.</li><li>Kullanıcı bilet almak istediğinde stok kontrolü ve düşme işlemi önce Redis’te yapılır.</li><li>Stok Redis’te başarıyla düştüyse istek bir <strong>Queue (RabbitMQ, Kafka vb.)</strong> yapısına atılır ve arka planda SQL veritabanına INSERT order olarak kaydedilir.</li></ul><pre>[İstek] ──► [Redis DECRBY] ──(Stok Var)──► [Message Queue] ──► [Async SQL Insert]</pre><h3>2. Stok Parçalama (Stock Sharding)</h3><p>Eğer illa SQL kullanmak zorundaysak, tek bir satırdaki kilit rekabetini azaltmanın cin bir yolu vardır: <strong>Kilit alanını bölmek!</strong></p><p>Stok değerini tek bir satırda tutmak yerine, örneğin 10 farklı satıra böleriz:</p><pre>+---------------+--------------+-----------+<br>|   Bucket ID   |   Match ID   |   Stock   |<br>|---------------+--------------+-----------|<br>|        1      |       42     |    6200   |<br>|        2      |       42     |    6200   |<br>|        3      |       42     |    6200   |<br>|       ...     |       42     |    6200   |<br>|       10      |       42     |    6200   |<br>+---------------+--------------+-----------+</pre><p>Uygulamanız bilet satarken rastgele bir Bucket ID seçer ve o satırı günceller. Böylece 5.000 isteğin oluşturduğu kilit rekabeti 10 farklı satıra bölünür ve kilit baskısı %90 azalır.</p><h3>3. İyimser Kilitleme (Optimistic Locking)</h3><p>Veritabanının satırı kilitlemesine izin vermek yerine (Pessimistic Locking), işlem sırasına bir version veya timestamp ekleriz.</p><pre>UPDATE tickets <br>SET stock = stock - 1, version = version + 1 <br>WHERE match_id = 42 AND version = 3;</pre><p>Eğer ilk istek başarılı olursa version 4 olur. Aynı anda gelen diğer istekler version = 3 şartını sağlayamadığı için kilit beklemez, anında başarısız olur. Uygulama katmanında bu başarısız istekler yakalanıp tekrar denetilebilir (retry mekanizması).</p><h3>Özetle</h3><p>Eşkin Market Bayır Turbanspor maçını yönetmek kolaydır; asıl mühendislik Barcelona — Real Madrid maçı geldiğinde başlar.</p><p>SQL’in sunduğu row-level locking harika bir güvenlik ağıdır ancak <strong>yüksek eşzamanlılık (concurrency)</strong> gerektiren durumlarda en büyük darboğazınız haline gelir. Sistem tasarlarken sıcak satırları tespit etmek ve bu yükü SQL dışına (Redis, Queue vb.) veya dağıtık yapılara yaymak, geceleri rahat uyumanızı sağlayacaktır.</p><p>Bir sonraki yazıda görüşmek üzere! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a316f705f12" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>