<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Visual Studio Learn</title>
    <description>The latest articles on DEV Community by Visual Studio Learn (@visualstudiolearn).</description>
    <link>https://dev.to/visualstudiolearn</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4221287%2F459827c7-0870-405c-94db-087d6bf8b535.png</url>
      <title>DEV Community: Visual Studio Learn</title>
      <link>https://dev.to/visualstudiolearn</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/visualstudiolearn"/>
    <language>en</language>
    <item>
      <title>Why Is My SQL Server Slow? A 4-Step Diagnosis with Blocking, Wait Stats, Execution Plans and Missing Indexes</title>
      <dc:creator>Visual Studio Learn</dc:creator>
      <pubDate>Sun, 15 Nov 2026 12:41:38 +0000</pubDate>
      <link>https://dev.to/visualstudiolearn/why-is-my-sql-server-slow-a-4-step-diagnosis-with-blocking-wait-stats-execution-plans-and-45e5</link>
      <guid>https://dev.to/visualstudiolearn/why-is-my-sql-server-slow-a-4-step-diagnosis-with-blocking-wait-stats-execution-plans-and-45e5</guid>
      <description>&lt;p&gt;&lt;strong&gt;Your SQL Server is slow — but "slow" is a symptom, not a diagnosis.&lt;/strong&gt; In this tutorial you will diagnose one genuinely slow query the way a mechanic finds a car fault: with &lt;strong&gt;four checks, in a fixed order&lt;/strong&gt;, each producing evidence instead of a guess. The four checks are: &lt;strong&gt;(1) is anything blocking the query, (2) what is the server waiting on, (3) what does the execution plan say, and (4) which index is missing.&lt;/strong&gt; Our test query starts out touching &lt;strong&gt;12,388 pages&lt;/strong&gt; to return about 2,061 rows. By the end of this post it touches &lt;strong&gt;15 pages&lt;/strong&gt; — and you will know exactly which check found the problem, because every number here was measured on the demo server while writing this post.&lt;/p&gt;

&lt;h2&gt;
  
  
  What you need
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;A SQL Server you can practise on — this post uses &lt;strong&gt;SQL Server 2025 (17.x)&lt;/strong&gt;, measured build 17.0.5065.9 (RTM-CU11) on Linux, driven from a terminal with &lt;code&gt;sqlcmd&lt;/code&gt;. Every query below also runs unchanged in a query window in &lt;strong&gt;SQL Server Management Studio (SSMS) 22&lt;/strong&gt; on Windows — a section near the end maps each step to SSMS.&lt;/li&gt;
&lt;li&gt;A throwaway database you may break. We create one below called &lt;code&gt;DemoDb&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Permission to see the server's diagnostic views: the wait and blocking views used here need the &lt;code&gt;VIEW SERVER PERFORMANCE STATE&lt;/code&gt; permission (on your own demo instance, your admin login already has it).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;No downloads beyond the database engine itself. Everything in this diagnosis is built into SQL Server.&lt;/p&gt;

&lt;h2&gt;
  
  
  The whole method, on one screen
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F6fbt2lyd1xd63aj2e43q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F6fbt2lyd1xd63aj2e43q.png" alt="The four-check flow map — slow query, blocking, waits, plan, missing index, fix and measure again" width="800" height="325"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Keep this map in mind. Each check below answers exactly one question, and each ends with evidence on screen: a row from a diagnostic view, an operator in a plan, or a count of pages read. Nothing is fixed by guessing.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 0 — Build the slow scene
&lt;/h2&gt;

&lt;p&gt;We need a table big enough to be slow and a query simple enough to reason about. Create the database and an &lt;code&gt;Orders&lt;/code&gt; table with 200,000 rows — orders from eight Canadian cities — with &lt;strong&gt;no index on the &lt;code&gt;City&lt;/code&gt; column&lt;/strong&gt;. That missing index is the planted fault; everything else about the setup is ordinary.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt; &lt;span class="k"&gt;DATABASE&lt;/span&gt; &lt;span class="nc"&gt;DemoDb&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="no"&gt;GO&lt;/span&gt;
&lt;span class="no"&gt;USE&lt;/span&gt; &lt;span class="nc"&gt;DemoDb&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="no"&gt;GO&lt;/span&gt;
&lt;span class="k"&gt;CREATE&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="n"&gt;dbo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Orders&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nc"&gt;OrderId&lt;/span&gt;     &lt;span class="kt"&gt;INT&lt;/span&gt; &lt;span class="no"&gt;IDENTITY&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;CONSTRAINT&lt;/span&gt; &lt;span class="nc"&gt;PK_Orders&lt;/span&gt; &lt;span class="k"&gt;PRIMARY&lt;/span&gt; &lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nc"&gt;CustomerId&lt;/span&gt;  &lt;span class="kt"&gt;INT&lt;/span&gt;           &lt;span class="k"&gt;NOT&lt;/span&gt; &lt;span class="kc"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nc"&gt;City&lt;/span&gt;        &lt;span class="no"&gt;NVARCHAR&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;40&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;  &lt;span class="k"&gt;NOT&lt;/span&gt; &lt;span class="kc"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nc"&gt;OrderDate&lt;/span&gt;   &lt;span class="kt"&gt;DATE&lt;/span&gt;          &lt;span class="k"&gt;NOT&lt;/span&gt; &lt;span class="kc"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nc"&gt;Total&lt;/span&gt;       &lt;span class="kt"&gt;DECIMAL&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;NOT&lt;/span&gt; &lt;span class="kc"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="nc"&gt;Notes&lt;/span&gt;       &lt;span class="no"&gt;NVARCHAR&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;300&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;NOT&lt;/span&gt; &lt;span class="kc"&gt;NULL&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="no"&gt;GO&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Fill it with generated rows (the full setup script, including the row generator, is in the companion code at the end of this post). Toronto is deliberately rare — about one percent of the table — because a city report is exactly the kind of query a real application runs.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvdxy8fkg1rpxrk5mhle3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvdxy8fkg1rpxrk5mhle3.png" alt="Step screenshot C1" width="800" height="710"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The demo instance reporting its version, and the finished table: 200,000 orders, 2,061 of them in Toronto.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 1 — Run the hero query and take its fingerprints
&lt;/h2&gt;

&lt;p&gt;Our hero query is the city report: &lt;em&gt;show me the orders from Toronto.&lt;/em&gt; Before diagnosing anything, measure it. Two counters matter:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Elapsed time&lt;/strong&gt; — how long the query took, in milliseconds.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Logical reads&lt;/strong&gt; — how many 8 KB &lt;em&gt;pages&lt;/em&gt; of the table SQL Server touched while answering. Pages are the honest yardstick: they do not depend on how fast your disk happens to be.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;SET&lt;/span&gt; &lt;span class="no"&gt;STATISTICS&lt;/span&gt; &lt;span class="no"&gt;IO&lt;/span&gt; &lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;SET&lt;/span&gt; &lt;span class="no"&gt;STATISTICS&lt;/span&gt; &lt;span class="kt"&gt;TIME&lt;/span&gt; &lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="nc"&gt;OrderId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;CustomerId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;OrderDate&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Total&lt;/span&gt;
&lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;dbo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Orders&lt;/span&gt;
&lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="nc"&gt;City&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;N&lt;/span&gt;&lt;span class="s1"&gt;'Toronto'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fwmmlj6hu9da86lms49uo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fwmmlj6hu9da86lms49uo.png" alt="Step screenshot C2" width="800" height="521"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;First run: elapsed **15 ms&lt;/em&gt;&lt;em&gt;, and **12,388 logical reads&lt;/em&gt;* — the server touched 12,388 pages to fetch about 2,061 rows. That ratio is the smell. Now we find out why, one check at a time.*&lt;/p&gt;

&lt;h2&gt;
  
  
  Check 1 — Is anything blocking it?
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;The idea in plain words.&lt;/strong&gt; When a query &lt;em&gt;changes&lt;/em&gt; a row, SQL Server &lt;em&gt;locks&lt;/em&gt; that row until the change is finished — like one person editing a shared document while everyone else waits. A &lt;em&gt;transaction&lt;/em&gt; is a group of changes treated as one unit: either all of them happen, or none do. If a transaction is left open, its locks stay held, and every other query that needs those rows queues behind it. On a busy server this — not a missing index — is the most common reason a healthy query suddenly "hangs".&lt;/p&gt;

&lt;p&gt;Prove it to yourself with two sessions. In session A, open a transaction, update one order, and deliberately leave the transaction open:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;BEGIN&lt;/span&gt; &lt;span class="k"&gt;TRANSACTION&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;UPDATE&lt;/span&gt; &lt;span class="n"&gt;dbo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Orders&lt;/span&gt; &lt;span class="k"&gt;SET&lt;/span&gt; &lt;span class="nc"&gt;Total&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Total&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt; &lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="nc"&gt;OrderId&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;42&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="c1"&gt;-- do NOT commit yet&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In session B, try to update the same order. It will not error and it will not finish — it waits. Now ask the engine who is waiting on whom. &lt;code&gt;sys.dm_exec_requests&lt;/code&gt; is the live list of work running right now, and its &lt;code&gt;blocking_session_id&lt;/code&gt; column names the session doing the blocking:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="n"&gt;session_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;blocking_session_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;wait_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;wait_time&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;status&lt;/span&gt;
&lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;dm_exec_requests&lt;/span&gt;
&lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;blocking_session_id&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fw3gehi1q0dvxf25i1r0m.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fw3gehi1q0dvxf25i1r0m.png" alt="Step screenshot C3" width="800" height="544"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Session A holding its transaction open; session B's update waiting behind it.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8jwlw2roenyxjhijpa5g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8jwlw2roenyxjhijpa5g.png" alt="Step screenshot C4" width="800" height="183"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The evidence: one row — session B, blocked by session A, waiting on a lock (an &lt;code&gt;LCK&lt;/code&gt; wait). Roll back session A's transaction and B completes instantly.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;In our hero query's case this check comes back clean — nobody is blocking it. Run this check first anyway, every time: &lt;strong&gt;no index in the world fixes a queue.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Check 2 — What is the server waiting on?
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;The idea in plain words.&lt;/strong&gt; SQL Server keeps a diary of waiting. Every time work pauses — for the disk, for a lock, for the processor — it writes down &lt;em&gt;why&lt;/em&gt; and &lt;em&gt;for how long&lt;/em&gt;. That diary is the view &lt;code&gt;sys.dm_os_wait_stats&lt;/code&gt;, accumulated since the server started. Ask it for the largest waits, skipping the idle background waits every healthy server records (the query in the companion code carries the standard filter list):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="no"&gt;TOP&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;8&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="n"&gt;wait_type&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;waiting_tasks_count&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;wait_time_ms&lt;/span&gt;
&lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;dm_os_wait_stats&lt;/span&gt;
&lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;wait_time_ms&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;
  &lt;span class="cm"&gt;/* ...plus the standard idle-wait filter, in the companion code... */&lt;/span&gt;
&lt;span class="k"&gt;ORDER&lt;/span&gt; &lt;span class="k"&gt;BY&lt;/span&gt; &lt;span class="n"&gt;wait_time_ms&lt;/span&gt; &lt;span class="k"&gt;DESC&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fm9p5hpob7ngyjiqi11ci.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fm9p5hpob7ngyjiqi11ci.png" alt="Step screenshot C5" width="800" height="489"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The top of our diary after the workload above: **LCK_M_X — 36,044 ms of lock waiting&lt;/em&gt;* across 3 waits. Further down: PAGEIOLATCH_SH — 337 ms across 285 waits for fetching data pages from disk into memory.*&lt;/p&gt;

&lt;p&gt;Read the diary honestly. The loudest entry is &lt;strong&gt;lock waiting — the fingerprint of Check 1&lt;/strong&gt;: the blocking we staged on purpose is the biggest single use of waiting time on this young demo server (36 seconds of it, while the blocking transaction sat open). That is the diary doing its job: it confirms the symptom and timestamps it. The page-fetch wait, &lt;code&gt;PAGEIOLATCH_SH&lt;/code&gt;, is present but small — 337 ms — because this demo's disk is fast and the table fits in memory after the first read. On a busy production server with a cold cache, a full-table scan like our hero query's pushes exactly that wait to the top of the diary; here, the 12,388 logical reads from Step 1 are the harder evidence. Two cautions that make you better at reading any diary: it accumulates &lt;em&gt;since the server started&lt;/em&gt; (know what workload it covers — ours includes our own staged blocking), and waits tell you &lt;em&gt;where&lt;/em&gt; time went, not &lt;em&gt;why&lt;/em&gt;. The why is the next check.&lt;/p&gt;

&lt;h2&gt;
  
  
  Check 3 — What does the execution plan say?
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;The idea in plain words.&lt;/strong&gt; Before running a query, SQL Server writes an &lt;em&gt;execution plan&lt;/em&gt; — the route it will take through the data. The &lt;em&gt;actual&lt;/em&gt; execution plan shows the route it really took, operator by operator. Two operators decide today's story:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Scan&lt;/strong&gt; — read every row in the table, one by one. With 200,000 rows, that is the whole book, page by page.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Seek&lt;/strong&gt; — use an &lt;em&gt;index&lt;/em&gt; (a sorted lookup list, like the index at the back of a book) and jump straight to the matching rows.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Ask for the actual plan of the hero query (in SSMS this is the &lt;em&gt;Include Actual Execution Plan&lt;/em&gt; button, or Ctrl+M; in a terminal, &lt;code&gt;SET STATISTICS XML ON&lt;/code&gt; returns the same plan):&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8536rk0iybbj706n9piy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8536rk0iybbj706n9piy.png" alt="Step screenshot C6" width="800" height="362"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The plan's heavy operator: **Clustered Index Scan&lt;/em&gt;&lt;em&gt;. The server read the entire table because, with no index on &lt;code&gt;City&lt;/code&gt;, a scan was the only route it had.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Check 4 — Which index is missing?
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;The idea in plain words.&lt;/strong&gt; Every time the planner wanted an index that did not exist, it wrote a note: the table, the columns it wanted, and how much it estimated the index would help. Those notes live in three views whose names start with &lt;code&gt;sys.dm_db_missing_index&lt;/code&gt;. Ask for the notes about our database:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="n"&gt;migs&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;avg_total_user_cost&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;migs&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;avg_user_impact&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;migs&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;user_seeks&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
       &lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;statement&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;equality_columns&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
       &lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;inequality_columns&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;included_columns&lt;/span&gt;
&lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;dm_db_missing_index_group_stats&lt;/span&gt; &lt;span class="k"&gt;AS&lt;/span&gt; &lt;span class="n"&gt;migs&lt;/span&gt;
&lt;span class="k"&gt;JOIN&lt;/span&gt; &lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;dm_db_missing_index_groups&lt;/span&gt;  &lt;span class="k"&gt;AS&lt;/span&gt; &lt;span class="n"&gt;mig&lt;/span&gt;
  &lt;span class="k"&gt;ON&lt;/span&gt; &lt;span class="n"&gt;migs&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;group_handle&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mig&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;index_group_handle&lt;/span&gt;
&lt;span class="k"&gt;JOIN&lt;/span&gt; &lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;dm_db_missing_index_details&lt;/span&gt; &lt;span class="k"&gt;AS&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt;
  &lt;span class="k"&gt;ON&lt;/span&gt; &lt;span class="n"&gt;mig&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;index_handle&lt;/span&gt;  &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;index_handle&lt;/span&gt;
&lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;mid&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;database_id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;DB_ID&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'DemoDb'&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;ORDER&lt;/span&gt; &lt;span class="k"&gt;BY&lt;/span&gt; &lt;span class="n"&gt;migs&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;avg_user_impact&lt;/span&gt; &lt;span class="k"&gt;DESC&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F7a217kim5504vmxu6b94.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F7a217kim5504vmxu6b94.png" alt="Step screenshot C7" width="800" height="185"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;SQL Server's own note: for &lt;code&gt;dbo.Orders&lt;/code&gt;, an index whose key is &lt;code&gt;[City]&lt;/code&gt;, with included columns [CustomerId], [OrderDate], [Total] — estimated improvement **98.19%&lt;/em&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The honesty rule&lt;/strong&gt; (Microsoft's own documentation says it plainly): a missing-index suggestion is &lt;em&gt;a hint, not a prescription&lt;/em&gt;. The estimates are made when the query is planned, before it runs, and the suggestions are forgotten when the server restarts. So read the note critically. Ours passes the common-sense test — the suggested key is exactly our query's filter column — so we build it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 5 — Create the index the server asked for
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt; &lt;span class="no"&gt;NONCLUSTERED&lt;/span&gt; &lt;span class="k"&gt;INDEX&lt;/span&gt; &lt;span class="nc"&gt;IX_Orders_City&lt;/span&gt;
&lt;span class="k"&gt;ON&lt;/span&gt; &lt;span class="n"&gt;dbo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Orders&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;City&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="no"&gt;INCLUDE&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;CustomerId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;OrderDate&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Total&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5v78kvf34cx6dua36wvl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F5v78kvf34cx6dua36wvl.png" alt="Step screenshot C8" width="799" height="167"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;The index builds in 524 ms. One line of SQL — chosen from evidence, not from a guess.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 6 — Run the same query again (the proof)
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;SET&lt;/span&gt; &lt;span class="no"&gt;STATISTICS&lt;/span&gt; &lt;span class="no"&gt;IO&lt;/span&gt; &lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;SET&lt;/span&gt; &lt;span class="no"&gt;STATISTICS&lt;/span&gt; &lt;span class="kt"&gt;TIME&lt;/span&gt; &lt;span class="k"&gt;ON&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="nc"&gt;OrderId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;CustomerId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;OrderDate&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Total&lt;/span&gt;
&lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;dbo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Orders&lt;/span&gt;
&lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="nc"&gt;City&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;N&lt;/span&gt;&lt;span class="s1"&gt;'Toronto'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8gae5f4tpvemi5yammfz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8gae5f4tpvemi5yammfz.png" alt="Step screenshot C9" width="800" height="534"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fmkgxla3rm7dkxob1daer.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fmkgxla3rm7dkxob1daer.png" alt="Step screenshot C10" width="800" height="332"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;After: the plan's heavy operator is now **Index Seek (on the new IX_Orders_City index)&lt;/em&gt;* — the server opens the book at the right page.*&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Measure&lt;/th&gt;
&lt;th&gt;Before&lt;/th&gt;
&lt;th&gt;After&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Elapsed time&lt;/td&gt;
&lt;td&gt;15 ms&lt;/td&gt;
&lt;td&gt;1 ms&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Logical reads (pages touched)&lt;/td&gt;
&lt;td&gt;12,388&lt;/td&gt;
&lt;td&gt;15&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Plan's main operator&lt;/td&gt;
&lt;td&gt;Clustered Index Scan&lt;/td&gt;
&lt;td&gt;Index Seek (on the new IX_Orders_City index)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;Same data. Same query, word for word. The only change is the index — added because four checks, in order, pointed at it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Doing this in SSMS
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Plans:&lt;/strong&gt; press &lt;strong&gt;Ctrl+M&lt;/strong&gt; (Include Actual Execution Plan), run the query, and read the Execution Plan tab — the operators you met above appear by name. A plan can also carry a green "Missing Index" suggestion line; right-clicking it offers the same CREATE INDEX the DMVs described.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Blocking:&lt;/strong&gt; Activity Monitor (right-click the server → Activity Monitor) shows blocked sessions in its Processes grid; the DMV query in Check 1 is the same information, scriptable.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Reads:&lt;/strong&gt; &lt;code&gt;SET STATISTICS IO ON&lt;/code&gt; prints its lines on the Messages tab, exactly as captured here.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Common mistakes
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Adding indexes by vibes.&lt;/strong&gt; Every index speeds some reads and slows every write to the table. Evidence first (Checks 1–4), then one index at a time, then re-measure.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Creating every suggested index.&lt;/strong&gt; Suggestions overlap and pile up; Microsoft calls them hints for a reason. Consolidate, and check what your queries actually filter on.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Blaming the index for a queue.&lt;/strong&gt; If Check 1 shows a blocker, the fix is the blocking transaction — not an index.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Tuning from a cold diary.&lt;/strong&gt; Wait stats and missing-index notes reset when the server restarts. Diagnose on a server that has been running the real workload.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  The method, on one card
&lt;/h2&gt;

&lt;p&gt;Blocked? Ask &lt;code&gt;sys.dm_exec_requests&lt;/code&gt;. Waiting? Ask &lt;code&gt;sys.dm_os_wait_stats&lt;/code&gt;. Why? Read the actual execution plan. Missing? Ask the &lt;code&gt;sys.dm_db_missing_index&lt;/code&gt; views. Then fix &lt;em&gt;one&lt;/em&gt; thing and measure again. Four questions, in order, evidence at every step.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Your exercise:&lt;/strong&gt; on a test database, run a query you believe is slow. Take its fingerprints (Step 1), run the four checks, write down what each one says &lt;em&gt;before&lt;/em&gt; you change anything — then make the one fix the evidence supports and compare the numbers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Sources
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Microsoft Learn — &lt;em&gt;sys.dm_exec_requests (Transact-SQL)&lt;/em&gt;: the &lt;code&gt;blocking_session_id&lt;/code&gt; column and the blocked-requests example.&lt;/li&gt;
&lt;li&gt;Microsoft Learn — &lt;em&gt;sys.dm_os_wait_stats (Transact-SQL)&lt;/em&gt;: "You can use this aggregated view to diagnose performance issues with SQL Server"; lock waits indicate contention, page IO latch waits indicate IO response.&lt;/li&gt;
&lt;li&gt;Microsoft Learn — &lt;em&gt;sys.dm_db_missing_index_details&lt;/em&gt; and &lt;em&gt;Tune nonclustered indexes with missing index suggestions&lt;/em&gt;: column roles, equality-before-inequality key order, and "suggestions aren't prescriptions".&lt;/li&gt;
&lt;li&gt;All timings, read counts and plan operators in this post were measured on the demo instance described in Step 0 while writing it.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Get the code
&lt;/h2&gt;

&lt;p&gt;The complete setup, diagnosis and fix scripts for this post live in the companion repository, in the folder for this topic, so you can rebuild the slow scene and run every check yourself.&lt;/p&gt;

</description>
      <category>sqlserver</category>
      <category>database</category>
      <category>performance</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Build Your Own Coding Agent in Python (It Fixes Real Code — Behind an Approval Gate)</title>
      <dc:creator>Visual Studio Learn</dc:creator>
      <pubDate>Thu, 12 Nov 2026 03:30:00 +0000</pubDate>
      <link>https://dev.to/visualstudiolearn/build-your-own-coding-agent-in-python-it-fixes-real-code-behind-an-approval-gate-1l6p</link>
      <guid>https://dev.to/visualstudiolearn/build-your-own-coding-agent-in-python-it-fixes-real-code-behind-an-approval-gate-1l6p</guid>
      <description>&lt;p&gt;Build your own coding agent — in one Python file, with three tools and one rule that makes it safe to use: &lt;strong&gt;it cannot change a single line of code until a human approves the change&lt;/strong&gt;. In this tutorial we build the agent on the Gemini API's function-calling loop, point it at a real project with a real failing test, and watch it find the bug, propose the fix, stop at the approval gate, and — only after a yes — apply it and prove the suite green. Then it prints its own bill. Every step has its own real screenshot, taken from the run you are reading about.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Versions used in this tutorial&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Python &lt;strong&gt;3.12&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;google-genai 3.0.0&lt;/strong&gt; (the Gemini SDK, pinned) and &lt;strong&gt;pytest 9.2.0&lt;/strong&gt; (pinned)&lt;/li&gt;
&lt;li&gt;Model: &lt;strong&gt;gemini-3.8-flash&lt;/strong&gt; — rate card verified on Google's official pricing page on 2026-11-07: $0.75 per 1M input tokens, $3.75 per 1M output tokens (Standard tier, in effect through Dec 31, 2026); a free tier exists&lt;/li&gt;
&lt;li&gt;Companion code: &lt;a href="https://github.com/sajjad037/visual-studio-learn-code/tree/main/topic-09-coding-agent" rel="noopener noreferrer"&gt;topic-09-coding-agent&lt;/a&gt; in the Visual Studio Learn code repo&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Step 0 — Setup from zero
&lt;/h2&gt;

&lt;p&gt;Nothing here assumes an existing project. You need Python 3.12, an isolated environment, the two pinned packages, and a free API key.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Create a &lt;strong&gt;venv&lt;/strong&gt; — a virtual environment, an isolated folder holding this project's packages so they never collide with the rest of your machine — and activate it:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;   &lt;span class="n"&gt;python3&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="n"&gt;venv&lt;/span&gt; &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;venv&lt;/span&gt;
   &lt;span class="n"&gt;source&lt;/span&gt; &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;venv&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="nb"&gt;bin&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;activate&lt;/span&gt;   &lt;span class="c1"&gt;# on Windows: .venv\Scripts\activate&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Install the pinned packages (the pins matter: this tutorial's code was verified against exactly these versions):
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;   &lt;span class="n"&gt;pip&lt;/span&gt; &lt;span class="n"&gt;install&lt;/span&gt; &lt;span class="n"&gt;google&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;genai&lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="mf"&gt;3.0&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt; &lt;span class="n"&gt;pytest&lt;/span&gt;&lt;span class="o"&gt;==&lt;/span&gt;&lt;span class="mf"&gt;9.2&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;In &lt;a href="https://aistudio.google.com" rel="noopener noreferrer"&gt;Google AI Studio&lt;/a&gt;, create a free API key, and put it in an &lt;strong&gt;environment variable&lt;/strong&gt; — a setting your terminal session carries — named &lt;code&gt;GEMINI_API_KEY&lt;/code&gt;:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;   &lt;span class="n"&gt;export&lt;/span&gt; &lt;span class="no"&gt;GEMINI_API_KEY&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;your&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;key&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;here&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The key goes in the environment, &lt;strong&gt;never in the code&lt;/strong&gt;. Code gets committed, shared and screenshotted; keys must not travel with it.&lt;/p&gt;

&lt;p&gt;One warning about free keys, from Google's own pricing page: on the &lt;strong&gt;free tier, content you send may be used to improve Google's products&lt;/strong&gt;. Learn on demo code, like this tutorial does — not on anything private.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fl2x6vsi8dcyxjkeb7ff1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fl2x6vsi8dcyxjkeb7ff1.png" alt="Terminal showing Python 3.12, the active venv, and the pinned google-genai and pytest installs completing" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Step 0: Python 3.12, the venv active, and the two pinned installs in place. The key is set in the environment — its value never appears on screen or in code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 1 — The patient: the buggy cart and its pytest suite
&lt;/h2&gt;

&lt;p&gt;The demo project (the &lt;code&gt;demo/&lt;/code&gt; folder in the companion code) is a tiny shopping cart. One bug lives in it on purpose, in &lt;code&gt;Cart.add()&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;add&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;unit_price_cents&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;quantity&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="c1"&gt;# BUG (planted): this replaces the quantity instead of adding to it.&lt;/span&gt;
    &lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;_items&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;unit_price_cents&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;quantity&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Add the same item twice and the quantity is &lt;em&gt;replaced&lt;/em&gt;, not accumulated. Around the cart sits a suite of four tests. Run it before the agent ever sees the project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="n"&gt;cd&lt;/span&gt; &lt;span class="n"&gt;demo&lt;/span&gt;
&lt;span class="n"&gt;python&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;m&lt;/span&gt; &lt;span class="n"&gt;pytest&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;q&lt;/span&gt;
&lt;span class="c1"&gt;# 1 failed, 3 passed&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The failing test — &lt;code&gt;test_add_same_item_twice_accumulates&lt;/code&gt; — adds two notebooks, then three more, and expects five; the cart says three. The other three tests — a new item, a mixed-cart total, a removal — all pass, so the bug is narrow: one method, one wrong idea about what "add" means. &lt;strong&gt;1 failed, 3 passed&lt;/strong&gt; is the contract for everything below: the agent's job is to turn that line into &lt;strong&gt;4 passed&lt;/strong&gt; without touching a test.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Flbigmo6l4xvrx3dsokp1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Flbigmo6l4xvrx3dsokp1.png" alt="Terminal running pytest on the untouched demo project: 1 failed, 3 passed, with the quantity test named as the failure" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Step 1, before: the untouched suite — exactly 1 failed, 3 passed. This is the result the agent has to change.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fblogger.googleusercontent.com%2Fimg%2Fb%2FR29vZ2xl%2FAVvXsEhbG5yJbn3MjtglcYRe9VX_GyIQB1wkfzOpgJM3US7xN-271vqcW3GOANud4EfqMZnNJ5XApJPaIispjE4cuqEmudBPQVoC9El6o53GKA_ZzBJJUrLHvJwgiOGwc8Vb4PWJ2KKX6AlJRUSU19FalS7vPQ3UDKnPwvmOwG934bBcs-7yPLvEDWP-e8G5-w%2Fs1600%2Fs2-patient.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fblogger.googleusercontent.com%2Fimg%2Fb%2FR29vZ2xl%2FAVvXsEhbG5yJbn3MjtglcYRe9VX_GyIQB1wkfzOpgJM3US7xN-271vqcW3GOANud4EfqMZnNJ5XApJPaIispjE4cuqEmudBPQVoC9El6o53GKA_ZzBJJUrLHvJwgiOGwc8Vb4PWJ2KKX6AlJRUSU19FalS7vPQ3UDKnPwvmOwG934bBcs-7yPLvEDWP-e8G5-w%2Fs1600%2Fs2-patient.png" alt="Editor showing cart.py with the planted add() bug and the failing assertion in test_cart.py" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The patient: &lt;code&gt;cart.py&lt;/code&gt;'s &lt;code&gt;add()&lt;/code&gt; replaces the quantity; the test beside it expects accumulation — 2 + 3 = 5.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 2 — The agent skeleton: client, model, task
&lt;/h2&gt;

&lt;p&gt;The whole agent is one file, &lt;code&gt;agent.py&lt;/code&gt;. Its head is the entire design in miniature:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;subprocess&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;sys&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;pathlib&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;Path&lt;/span&gt;

&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;google&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;genai&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;google&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;genai&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;types&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Every import the file needs sits at the top — &lt;code&gt;os&lt;/code&gt; for the key check, &lt;code&gt;subprocess&lt;/code&gt; and &lt;code&gt;sys&lt;/code&gt; for the test tool, &lt;code&gt;Path&lt;/code&gt; for the confinement check, and the SDK itself. Then the constants:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="no"&gt;PROJECT_DIR&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;Path&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;__file__&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parent&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="s2"&gt;"demo"&lt;/span&gt;
&lt;span class="no"&gt;MODEL&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"gemini-3.8-flash"&lt;/span&gt;
&lt;span class="no"&gt;MAX_STEPS&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;12&lt;/span&gt;

&lt;span class="no"&gt;TASK&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="s2"&gt;"Run the test suite in this project. If a test fails, read the test and "&lt;/span&gt;
    &lt;span class="s2"&gt;"the code it tests, find the bug, and fix the source file so the whole "&lt;/span&gt;
    &lt;span class="s2"&gt;"suite passes. Do not edit the tests. When every test passes, stop and "&lt;/span&gt;
    &lt;span class="s2"&gt;"summarise what the bug was and what you changed."&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Three ideas to notice. The &lt;strong&gt;model&lt;/strong&gt; is &lt;code&gt;gemini-3.8-flash&lt;/code&gt;, the current Flash model — fast, inexpensive, and it supports &lt;strong&gt;function calling&lt;/strong&gt;: the mechanism this whole tutorial is built on. The model never runs code itself; it asks our program to run named functions — &lt;em&gt;tools&lt;/em&gt; — and reads their results. The &lt;strong&gt;task&lt;/strong&gt; is plain English with two hard edges: fix the source, &lt;em&gt;never the tests&lt;/em&gt;. And &lt;code&gt;MAX_STEPS&lt;/code&gt; is a hard cap of twelve model turns, so a confused model costs twelve turns — never an infinite loop.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdolbd4f5zzwm23snnuac.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdolbd4f5zzwm23snnuac.png" alt="Editor showing the head of agent.py: the client, the gemini-3.8-flash model constant, the step cap, and the plain-English task" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Step 2: the skeleton — client, model, step cap, and the task written as instructions a careful junior would understand.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 3 — Tool 1: &lt;code&gt;read_file&lt;/code&gt;, confined
&lt;/h2&gt;

&lt;p&gt;An agent is only its tools, and ours has exactly three. The first reads a file and hands its text to the model:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;confine&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;path_text&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""Resolve a model-supplied path and refuse anything outside the project."""&lt;/span&gt;
    &lt;span class="n"&gt;path&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;PROJECT_DIR&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;path_text&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;is_relative_to&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="no"&gt;PROJECT_DIR&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;resolve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;path&lt;/span&gt;

&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;tool_read_file&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;target&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;confine&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;is_file&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"error"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"cannot read {path}"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"content"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;read_text&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="mi"&gt;8000&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The guard is the lesson: every path the model supplies is resolved and checked, and anything landing outside the demo project folder is refused. The model can &lt;em&gt;ask&lt;/em&gt; for anything; the code decides what it may touch. (We tested the escape: asking for a file two folders up — outside the project — comes back as an error, not a file.)&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fi233h3f3cvjltbbvt68i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fi233h3f3cvjltbbvt68i.png" alt="Editor showing the confine() path check and the read_file tool in agent.py" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Step 3: &lt;code&gt;confine()&lt;/code&gt; — every model-supplied path is resolved and refused if it escapes the project folder.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 4 — Tool 2: &lt;code&gt;run_tests&lt;/code&gt;
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;tool_run_tests&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="n"&gt;proc&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;subprocess&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;run&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;executable&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"-m"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"pytest"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"-q"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;cwd&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="no"&gt;PROJECT_DIR&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;capture_output&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;True&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;timeout&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;120&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"exit_code"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;proc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;returncode&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"output"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;proc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stdout&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;proc&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stderr&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;3000&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The second tool runs the suite with a fixed command — the model cannot alter it — inside the project folder, and returns the tail of the output, where pytest puts its summary. Tools 1 and 2 are read-only: watching and reading. Safe. The third tool is neither.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fn6twk4bax5gu0jhlli2q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fn6twk4bax5gu0jhlli2q.png" alt="Editor showing the run_tests tool: a fixed pytest subprocess call returning the exit code and the output tail" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Step 4: &lt;code&gt;run_tests&lt;/code&gt; — a fixed command the model can invoke but never modify.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 5 — Tool 3: &lt;code&gt;write_file&lt;/code&gt; and the approval gate
&lt;/h2&gt;

&lt;p&gt;This is the dangerous tool, so it is built differently. &lt;strong&gt;The model never writes. It proposes.&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;tool_write_file&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;content&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="s2"&gt;"""THE GATE: the model only ever PROPOSES. A human decides."""&lt;/span&gt;
    &lt;span class="n"&gt;target&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;confine&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;path&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt; &lt;span class="k"&gt;is&lt;/span&gt; &lt;span class="kc"&gt;None&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"error"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"refused: {path} is outside the project folder"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"\n--- The agent wants to write {path} ---"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;content&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;answer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;input&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Apply this change? [y/N] "&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;strip&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;lower&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;answer&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="s2"&gt;"y"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"--- Denied by the human. The file was NOT changed. ---"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"result"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"DENIED by the human approver. Do not retry this write; "&lt;/span&gt;
                          &lt;span class="s2"&gt;"explain in your summary what you wanted to change."&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;write_text&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;content&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"--- Approved and written. ---"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"result"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"{path} written"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The full proposed content is printed in the terminal, and the program stops at a yes/no prompt. Answer anything but &lt;code&gt;y&lt;/code&gt; and the file stays byte-for-byte untouched — and the model is told, in plain words, that a human refused and it must not retry. Only a yes writes. Every other tool in this agent can run all day; this one needs you.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1f8ssymeryp0wviw9cou.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F1f8ssymeryp0wviw9cou.png" alt="Editor showing the write_file tool: the proposal printout and the human yes-no approval prompt" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Step 5, in code: the model proposes; the &lt;code&gt;input()&lt;/code&gt; line is the gate — nothing writes before it returns "y".&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ffo82l7ib4ei0v66hm4g5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ffo82l7ib4ei0v66hm4g5.png" alt="Terminal at the real approval-gate moment of the run: the proposed file printed, the Apply this change prompt, and the approval being given" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Step 5, live: the gate fires during the real run. The proposed file is on screen; the file on disk has not changed yet.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 6 — The loop: manual function calling with the Gemini API
&lt;/h2&gt;

&lt;p&gt;Around the tools sits the loop. Each tool is declared to the model as a &lt;code&gt;FunctionDeclaration&lt;/code&gt; — a name, a plain-English description, and a schema of its arguments — and that declaration is all the model ever sees of the code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="no"&gt;DECLARATIONS&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;
    &lt;span class="n"&gt;types&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;FunctionDeclaration&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"read_file"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;description&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"Read a file inside the project folder."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;parameters&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;types&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Schema&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"OBJECT"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;properties&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="s2"&gt;"path"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;types&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Schema&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;type&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"STRING"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;description&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"File name, e.g. cart.py"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;required&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"path"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="c1"&gt;# … run_tests and write_file are declared the same way …&lt;/span&gt;
&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One small table ties the names to the functions — the loop looks each call up by name:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="no"&gt;TOOLS&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"read_file"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;tool_read_file&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"run_tests"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;tool_run_tests&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
         &lt;span class="s2"&gt;"write_file"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;tool_write_file&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And here is the loop itself — the whole of &lt;code&gt;main()&lt;/code&gt;, condensed only in its token-counting lines. Everything a working agent needs is on this screen:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;main&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;os&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;environ&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"GEMINI_API_KEY"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;exit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Set GEMINI_API_KEY first (free key from Google AI Studio)."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;genai&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Client&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;config&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;types&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;GenerateContentConfig&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="n"&gt;tools&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;types&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Tool&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;function_declarations&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="no"&gt;DECLARATIONS&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;contents&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;types&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Content&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;role&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"user"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;parts&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;types&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Part&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="no"&gt;TASK&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;

    &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;step&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="nb"&gt;range&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;MAX_STEPS&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="n"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;models&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;generate_content&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="n"&gt;model&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="no"&gt;MODEL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;contents&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;contents&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;config&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;config&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="c1"&gt;# … count response.usage_metadata tokens here (Step 8) …&lt;/span&gt;
        &lt;span class="n"&gt;model_content&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;candidates&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;content&lt;/span&gt;
        &lt;span class="n"&gt;contents&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;model_content&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

        &lt;span class="n"&gt;calls&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;function_call&lt;/span&gt; &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;model_content&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;parts&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;function_call&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="ow"&gt;not&lt;/span&gt; &lt;span class="n"&gt;calls&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;  &lt;span class="c1"&gt;# the model answered in words — the task is done&lt;/span&gt;
            &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"\nAGENT:"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;text&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;break&lt;/span&gt;
        &lt;span class="n"&gt;replies&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="n"&gt;call&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="n"&gt;calls&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"[step {step}] tool: {call.name} {dict(call.args or {})}"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;TOOLS&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;call&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;**&lt;/span&gt;&lt;span class="kt"&gt;dict&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;call&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;args&lt;/span&gt; &lt;span class="ow"&gt;or&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;replies&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;types&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Part&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;from_function_response&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;call&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;response&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;contents&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;append&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;types&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Content&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;role&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"user"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;parts&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="n"&gt;replies&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;else&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="k"&gt;print&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;f&lt;/span&gt;&lt;span class="s2"&gt;"\nStopped: step cap ({MAX_STEPS}) reached."&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Read it as a conversation with a bouncer. The task and the declarations go in; the model's answer comes back as either words (job done — break) or function calls. Each call is dispatched through the &lt;code&gt;TOOLS&lt;/code&gt; dictionary to the real Python function — &lt;code&gt;write_file&lt;/code&gt; included, gate and all — and every result goes back to the model in a &lt;code&gt;Content&lt;/code&gt; with role &lt;code&gt;"user"&lt;/code&gt; — the manual-loop pattern this API accepts. (Worth knowing: some write-ups send function results with a &lt;code&gt;"tool"&lt;/code&gt; role; on the live run for this post that came straight back as a 400 error, and &lt;code&gt;"user"&lt;/code&gt; is what worked. The code above is the code that ran.) The &lt;code&gt;for…else&lt;/code&gt; is the step cap doing its job: exhaust twelve steps without a words-only answer and the loop stops itself. This manual pattern is deliberate: automatic function calling hides exactly the moving parts a builder needs to see — and the SDK's own documentation is changing how automatic calling is invoked in the next major version, while the manual loop this tutorial teaches stays as documented.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F97g106gu2brlxs33m13g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F97g106gu2brlxs33m13g.png" alt="Editor showing the main() loop in agent.py: the generate_content call, the function-call dispatch, and the step cap" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Step 6: the loop — send, dispatch, return the result, repeat — capped at twelve steps.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 7 — The run
&lt;/h2&gt;

&lt;p&gt;Now the real run, on the machine this post was written on, unedited.&lt;/p&gt;

&lt;p&gt;The agent's first move is &lt;code&gt;run_tests&lt;/code&gt; — it sees the failure itself: &lt;strong&gt;1 failed, 3 passed&lt;/strong&gt;. Then it reads both files: the failing test, then &lt;code&gt;cart.py&lt;/code&gt;. It names the bug in one sentence: &lt;code&gt;add()&lt;/code&gt; replaces the quantity instead of accumulating. Then the proposal arrives — and the run stops cold at the gate. The proposed file is on screen; nothing on disk has changed. The proposed file changes only the &lt;code&gt;add&lt;/code&gt; method. Approve — the write lands — and the agent runs the suite again on its own: &lt;strong&gt;4 passed&lt;/strong&gt;. Found, diagnosed, proposed, approved, fixed, proven.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbog6orhip23bhn3vhwx8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbog6orhip23bhn3vhwx8.png" alt="Terminal transcript of the live run: the agent calling run_tests, reading the test and cart.py, and naming the bug" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Step 7: the run's first half — the agent finds the failure, reads both files, and diagnoses the bug itself.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fv610t6l0f57wor80xaiy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fv610t6l0f57wor80xaiy.png" alt="Terminal transcript of the live run after approval: the suite rerunning to 4 passed and the agent's summary" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Step 7, payoff: after the approval, the agent re-runs the suite on its own — 4 passed — and summarises the fix.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 8 — The bill
&lt;/h2&gt;

&lt;p&gt;An agent you cannot price is an agent you cannot plan around, so the agent counts its own tokens: every model turn reports its usage, and the program adds them up and prices them at the rate card. This run used &lt;strong&gt;7,017 tokens in&lt;/strong&gt; and &lt;strong&gt;1,202 tokens out&lt;/strong&gt; — output counted including thinking tokens, because that is how the official rate card bills them — for a total of about &lt;strong&gt;$0.0098&lt;/strong&gt; at $0.75 / $3.75 per million. The lesson is not that it is cheap; it is that the cost is &lt;em&gt;knowable&lt;/em&gt;, per run, from numbers the run itself prints.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvc5k9xaggl5ftt5tx036.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvc5k9xaggl5ftt5tx036.png" alt="Terminal showing the run's closing line: the token counts and the computed cost of the fix" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Step 8: the run prints its own bill — real token counts from the run's usage metadata, priced at the verified rate card.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 9 — Guardrails: code, not prompts
&lt;/h2&gt;

&lt;p&gt;Name the guardrails, because they are the difference between a tool and a liability:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;The approval gate&lt;/strong&gt; — no write is ever ungated; a refusal is final and the model is told not to retry.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Confinement&lt;/strong&gt; — every tool is locked to one project folder, enforced by the resolved-path check in code, not requested in a prompt.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The step cap&lt;/strong&gt; — twelve turns, then it stops, whatever it believes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;What the agent does not have&lt;/strong&gt; — no shell tool, so it cannot run arbitrary commands; no network tool, so it cannot send your code anywhere.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;These are the same patterns the serious tools use: Claude Code confines its writes and asks before dangerous actions, and approval-routing designs send a risky action to a human before it is allowed to execute. Prompts are suggestions. Code is enforcement. Build the enforcement.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 10 — The honest verdict
&lt;/h2&gt;

&lt;p&gt;What it nailed: the diagnosis was exact, the patch minimal, and it stopped when the suite went green instead of gold-plating. Where it wobbled: it rewrote the whole file to change three lines in one method — whole-file writes are simple, but blunt — and the file it saved still carries its header comment claiming a bug lives here on purpose, which stopped being true the moment the fix landed. That is what the gate is for: a human reading the proposal catches the stale comment; an auto-approver ships it. And the limits, plainly: this is a teaching agent for small, well-tested code. A full tool brings a terminal, a whole-codebase index, and years of hardening this one file does not have. Build one anyway — not to replace those tools, but because the day you have written the loop, the gate, and the confinement yourself, you understand what every agent product is actually doing under the hood. That understanding is the real deliverable.&lt;/p&gt;

&lt;h2&gt;
  
  
  Errors you may hit
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Bad or expired key&lt;/strong&gt; — the program stops before anything runs (&lt;code&gt;Set GEMINI_API_KEY first&lt;/code&gt;). Set the variable in the same terminal you run the agent from.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The model repeats a tool call&lt;/strong&gt; — the step cap ends the loop at twelve. Read the transcript; the fix is usually a clearer task sentence.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;A patch breaks a different test&lt;/strong&gt; — the suite goes red again and the loop continues, and the gate gives you a second decision. Never approve a fix you have not read.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;pytest&lt;/code&gt; not found&lt;/strong&gt; — your venv is not active. Activate it, and run the agent from the project folder.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Go further: the agent files its own report (GitHub MCP)
&lt;/h2&gt;

&lt;p&gt;The companion video's Short takes one more step: after the fix, the agent opens &lt;a href="https://github.com/sajjad037/visual-studio-learn-code/issues/16" rel="noopener noreferrer"&gt;issue #16&lt;/a&gt; in this blog's code repo, summarising the bug and the fix — through GitHub's official MCP server, and it asks at the gate before posting. The server is &lt;strong&gt;remote&lt;/strong&gt;, hosted by GitHub at &lt;code&gt;https://api.githubcopilot.com/mcp/&lt;/code&gt;; for an issues-only connection you can scope it to &lt;code&gt;https://api.githubcopilot.com/mcp/x/issues&lt;/code&gt;. Authenticate with a &lt;strong&gt;fine-grained personal access token&lt;/strong&gt; — a PAT: an API password whose permissions you can limit — &lt;strong&gt;scoped to the one repository, with Issues set to Read and write&lt;/strong&gt;. Least privilege, exactly like the confinement in Step 3. The google-genai SDK can also consume an MCP session directly as a tool (its docs mark the support experimental); either way, the rule from Step 5 travels with it: an outward-facing write gets a human gate first.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvbe141p8qcggwrgwue6l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fvbe141p8qcggwrgwue6l.png" alt="Browser showing the GitHub issue the agent opened in the visual-studio-learn-code repo, summarising the bug and the fix" width="800" height="450"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The artifact: the issue the agent filed in the repo after the fix — proposed, approved at the gate, then posted.&lt;/p&gt;

&lt;h2&gt;
  
  
  Sources
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Google, &lt;a href="https://ai.google.dev/gemini-api/docs/pricing" rel="noopener noreferrer"&gt;Gemini Developer API pricing&lt;/a&gt; — the gemini-3.8-flash rate card and the free-tier data-use note (accessed 2026-11-07).&lt;/li&gt;
&lt;li&gt;Google, &lt;a href="https://googleapis.github.io/python-genai/" rel="noopener noreferrer"&gt;Google Gen AI SDK documentation&lt;/a&gt; — the manual function-calling pattern, FunctionDeclaration, and function-response roles (accessed 2026-11-07).&lt;/li&gt;
&lt;li&gt;GitHub, &lt;a href="https://github.com/github/github-mcp-server" rel="noopener noreferrer"&gt;github/github-mcp-server&lt;/a&gt; — the remote MCP endpoint, toolsets, and token guidance (accessed 2026-11-07).&lt;/li&gt;
&lt;li&gt;Google AI Studio — &lt;a href="https://aistudio.google.com" rel="noopener noreferrer"&gt;aistudio.google.com&lt;/a&gt; (free API keys).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Companion code:&lt;/strong&gt; the complete agent, the demo project, and the tests are free in the repo folder linked at the top of this post. The companion video walks the same build on the real screens.&lt;/p&gt;

</description>
      <category>python</category>
      <category>gemini</category>
      <category>ai</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Monitor a FastAPI App with Prometheus + Grafana (Metrics, Dashboards, Alerts)</title>
      <dc:creator>Visual Studio Learn</dc:creator>
      <pubDate>Wed, 11 Nov 2026 13:45:16 +0000</pubDate>
      <link>https://dev.to/visualstudiolearn/monitor-a-fastapi-app-with-prometheus-grafana-metrics-dashboards-alerts-4if5</link>
      <guid>https://dev.to/visualstudiolearn/monitor-a-fastapi-app-with-prometheus-grafana-metrics-dashboards-alerts-4if5</guid>
      <description>&lt;p&gt;Your FastAPI app is slow, and you cannot see it. There is no graph of your traffic, no counter of your errors, and nothing that tells you &lt;em&gt;which&lt;/em&gt; endpoint is the slow one. The first symptom is a user complaint — and by then you are debugging blind.&lt;/p&gt;

&lt;p&gt;In this tutorial you will fix that, end to end, on your own machine: instrument a FastAPI app so it publishes its own metrics, collect them with Prometheus, and build a Grafana dashboard that catches a slow endpoint live — then set an alert that fires when it happens again. Everything is local and free: no accounts, no API keys, no cloud.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What we are using&lt;/strong&gt; (pinned, so your install matches this post exactly): prometheus-fastapi-instrumentator 8.1.0 · Prometheus 3.16.0 · Grafana OSS 13.3.0 · FastAPI 0.162.4 · uvicorn 0.54.0 · Python 3.12. The complete companion code — the app, the Prometheus config, the load script, the exported dashboard JSON and the alert rule — is in the &lt;a href="https://github.com/sajjad037/visual-studio-learn-code" rel="noopener noreferrer"&gt;companion repository&lt;/a&gt;, folder &lt;code&gt;topic-10-prometheus-grafana/&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fnqs5ezhaboqo23757qjt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fnqs5ezhaboqo23757qjt.png" alt="Grafana RED dashboard after the load burst" width="800" height="500"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 1 — Install the stack
&lt;/h2&gt;

&lt;p&gt;Create a virtual environment and install the app stack. The instrumentator is the only monitoring-specific package the app needs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;$ python -m venv venv &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="nb"&gt;source&lt;/span&gt; venv/bin/activate
$ pip install fastapi uvicorn prometheus-fastapi-instrumentator
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pin what you installed in a &lt;code&gt;requirements.txt&lt;/code&gt; (&lt;code&gt;fastapi==0.162.4&lt;/code&gt;, &lt;code&gt;uvicorn==0.54.0&lt;/code&gt;, &lt;code&gt;prometheus-fastapi-instrumentator==8.1.0&lt;/code&gt;, and &lt;code&gt;httpx==0.28.1&lt;/code&gt;, which the load script in Step 9 uses). Prometheus and Grafana themselves are single binaries you download from their official sites and run locally — no Docker required, which is how this post was produced.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 2 — The demo app: one endpoint per signal
&lt;/h2&gt;

&lt;p&gt;The demo app is deliberately small, with one endpoint per thing a dashboard should show you:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;asyncio&lt;/span&gt;

&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;fastapi&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;FastAPI&lt;/span&gt;
&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;fastapi&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;responses&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;JSONResponse&lt;/span&gt;

&lt;span class="n"&gt;app&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;FastAPI&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;title&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"Demo Shop API"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="nd"&gt;@app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;home&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;  &lt;span class="c1"&gt;# instant JSON — the healthy traffic&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"ok"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"service"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"demo-shop"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nd"&gt;@app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/slow"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;slow&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;  &lt;span class="c1"&gt;# sleeps 0.8s, then answers&lt;/span&gt;
    &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="n"&gt;asyncio&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sleep&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mf"&gt;0.8&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"status"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"ok"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"detail"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"that took a while"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nd"&gt;@app&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/boom"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="k"&gt;def&lt;/span&gt; &lt;span class="nf"&gt;boom&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;  &lt;span class="c1"&gt;# HTTP 500, every time&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nc"&gt;JSONResponse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;status_code&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="mi"&gt;500&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;content&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="p"&gt;{&lt;/span&gt;&lt;span class="s2"&gt;"detail"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"something broke"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That file is complete and runnable as written — it is the companion repo's &lt;code&gt;app.py&lt;/code&gt; minus the two monitoring lines, which are Step 3.&lt;/p&gt;

&lt;p&gt;Run it with &lt;code&gt;uvicorn app:app --port 8000&lt;/code&gt; and curl all three: &lt;code&gt;/&lt;/code&gt; answers instantly, &lt;code&gt;/slow&lt;/code&gt; takes 0.80s on the timer, and &lt;code&gt;/boom&lt;/code&gt; returns a clean HTTP 500. Nothing is monitored yet — that is the point. We are about to watch all three behaviours appear on a dashboard.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 3 — Instrument the app (two calls)
&lt;/h2&gt;

&lt;p&gt;This is the whole integration. Add the import and one line after you create the app:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight python"&gt;&lt;code&gt;&lt;span class="k"&gt;from&lt;/span&gt; &lt;span class="n"&gt;prometheus_fastapi_instrumentator&lt;/span&gt; &lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="nc"&gt;Instrumentator&lt;/span&gt;

&lt;span class="nc"&gt;Instrumentator&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;instrument&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;expose&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;instrument(app)&lt;/code&gt; wraps your app so every request is measured; &lt;code&gt;expose(app)&lt;/code&gt; serves those measurements at a new endpoint, &lt;code&gt;/metrics&lt;/code&gt;. Restart uvicorn, generate a few requests, and open &lt;code&gt;http://localhost:8000/metrics&lt;/code&gt; in your browser.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 4 — Read what /metrics gives you for free
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fqrhlt195g465nhvgra1a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fqrhlt195g465nhvgra1a.png" alt="The /metrics page" width="800" height="500"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Without writing a single metric yourself, the instrumentator publishes five defaults. The three that matter most:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;http_requests_total&lt;/code&gt; — a counter of every request, labelled by &lt;code&gt;handler&lt;/code&gt; (your endpoint), &lt;code&gt;status&lt;/code&gt; and &lt;code&gt;method&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;http_request_duration_seconds&lt;/code&gt; — a histogram of how long requests take, in buckets. This is where response-time percentiles come from.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;http_request_size_bytes&lt;/code&gt; and &lt;code&gt;http_response_size_bytes&lt;/code&gt; — request and response sizes.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;One gotcha to learn now, because it bites everyone:&lt;/strong&gt; the status label is &lt;em&gt;grouped&lt;/em&gt;. After hitting &lt;code&gt;/boom&lt;/code&gt;, the counter reads &lt;code&gt;http_requests_total{handler="/boom", status="5xx"}&lt;/code&gt; — there is no &lt;code&gt;status="500"&lt;/code&gt; series. Remember that when we write queries in Step 6, and again in the Traps section at the end.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fc2tjghf403941hmtb3m6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fc2tjghf403941hmtb3m6.png" alt="Duration histogram buckets" width="800" height="500"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The duration histogram's default buckets are &lt;code&gt;le = 0.1, 0.5, 1.0, +Inf&lt;/code&gt; seconds. A percentile computed from a histogram is an &lt;em&gt;interpolated estimate&lt;/em&gt; inside a bucket, not an exact measurement — keep that in mind when we read "0.975 seconds" in Step 9: it is the honest estimate the buckets support, and widening the buckets is how you trade precision for cost.&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 5 — Point Prometheus at the app
&lt;/h2&gt;

&lt;p&gt;Prometheus &lt;em&gt;pulls&lt;/em&gt; metrics: every few seconds it fetches &lt;code&gt;/metrics&lt;/code&gt; and stores the numbers as time series. Create &lt;code&gt;prometheus.yml&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;global&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;scrape_interval&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;5s&lt;/span&gt;   &lt;span class="c1"&gt;# a demo choice — the default is 1m
&lt;/span&gt;
&lt;span class="na"&gt;scrape_configs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
  &lt;span class="p"&gt;-&lt;/span&gt; &lt;span class="na"&gt;job_name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;fastapi&lt;/span&gt;
    &lt;span class="na"&gt;static_configs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="p"&gt;-&lt;/span&gt; &lt;span class="na"&gt;targets&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"localhost:8000"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The 5-second scrape interval is a deliberate demo choice so the dashboard moves while you watch; in production, 15–60 seconds is normal. Start Prometheus with this config (&lt;code&gt;./prometheus --config.file=prometheus.yml&lt;/code&gt; from the folder you extracted it to), then open &lt;code&gt;http://localhost:9090/targets&lt;/code&gt;: the &lt;code&gt;fastapi&lt;/code&gt; target must read &lt;strong&gt;UP&lt;/strong&gt;. If it reads DOWN, stop and fix that first — every later step depends on it (see Traps).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdc6ofb3m2dn6hvahokxb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdc6ofb3m2dn6hvahokxb.png" alt="Prometheus targets UP" width="800" height="500"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 6 — Ask three questions with PromQL
&lt;/h2&gt;

&lt;p&gt;Monitoring dashboards are built from three questions — the &lt;strong&gt;RED method&lt;/strong&gt;: &lt;strong&gt;Rate&lt;/strong&gt; (how much traffic am I getting?), &lt;strong&gt;Errors&lt;/strong&gt; (how much of it is failing?), &lt;strong&gt;Duration&lt;/strong&gt; (how slow is it?). Each one is a single Prometheus query. Try them in Prometheus's own graph tab first (&lt;code&gt;http://localhost:9090/graph&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Rate&lt;/strong&gt; — requests per second, per endpoint. &lt;code&gt;rate(...)&lt;/code&gt; turns the ever-growing counter into a per-second rate over a window — here, the last 5 minutes:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight prometheus"&gt;&lt;code&gt;&lt;span class="na"&gt;sum by (handler) (rate(http_requests_total{handler!&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"/metrics"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;handler&lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="s2"&gt;"none"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;5m&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fblogger.googleusercontent.com%2Fimg%2Fb%2FR29vZ2xl%2FAVvXsEhmOqOUNYpWVjgVHJYAmTo72Ktb54Tsb_DXHTszGX_ODuqxoIfr_jRfFqZtjm2XhjJfzW8GnlNNGy76htmXcm1DXmEsyXBAMPuzC8A90fQ0ih8BSseoTnXNQREP5qbaE_F49sYw82MfQJyl8BC4cmcaHK9xH0C8w6nl1FF6MFNS2PmyL99-T-fbE9S8Ohg%2Fs1600%2Fpromql-rate-query-graph.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fblogger.googleusercontent.com%2Fimg%2Fb%2FR29vZ2xl%2FAVvXsEhmOqOUNYpWVjgVHJYAmTo72Ktb54Tsb_DXHTszGX_ODuqxoIfr_jRfFqZtjm2XhjJfzW8GnlNNGy76htmXcm1DXmEsyXBAMPuzC8A90fQ0ih8BSseoTnXNQREP5qbaE_F49sYw82MfQJyl8BC4cmcaHK9xH0C8w6nl1FF6MFNS2PmyL99-T-fbE9S8Ohg%2Fs1600%2Fpromql-rate-query-graph.png" alt="PromQL rate graph" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Errors&lt;/strong&gt; — the share of responses that are 5xx. Note the grouped label from Step 4: the numerator selects &lt;code&gt;status="5xx"&lt;/code&gt;, because &lt;code&gt;status="500"&lt;/code&gt; does not exist:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight prometheus"&gt;&lt;code&gt;&lt;span class="na"&gt;sum(rate(http_requests_total{status&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"5xx"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;5m&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="o"&gt;/&lt;/span&gt;
&lt;span class="na"&gt;sum(rate(http_requests_total{handler!&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"/metrics"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;5m&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Duration&lt;/strong&gt; — the 95th percentile response time, per endpoint. Read it as: "95% of requests were faster than this." &lt;code&gt;histogram_quantile&lt;/code&gt; does the bucket interpolation for you:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight prometheus"&gt;&lt;code&gt;&lt;span class="nf"&gt;histogram_quantile&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mf"&gt;0.95&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="na"&gt;sum by (handler, le) (rate(http_request_duration_seconds_bucket{handler!&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="s2"&gt;"/metrics"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;handler&lt;/span&gt;&lt;span class="o"&gt;!=&lt;/span&gt;&lt;span class="s2"&gt;"none"&lt;/span&gt;&lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="mi"&gt;5m&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fblogger.googleusercontent.com%2Fimg%2Fb%2FR29vZ2xl%2FAVvXsEiW6b8U4P3yR2fz9KEzc_iz2GCJtBXJKc7SsUV6xYvu2Lj-1X31XDLzAqn8pH1NBMVZ5UMPvxnbkBGy-4JxKp-f48o5H93aCvPCuMXbpL2yoGeteImc76S8Vzwzjj2nC_Yg0BAd9_ps%2Fs1600%2Fpromql-p95-histogram-quantile.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fblogger.googleusercontent.com%2Fimg%2Fb%2FR29vZ2xl%2FAVvXsEiW6b8U4P3yR2fz9KEzc_iz2GCJtBXJKc7SsUV6xYvu2Lj-1X31XDLzAqn8pH1NBMVZ5UMPvxnbkBGy-4JxKp-f48o5H93aCvPCuMXbpL2yoGeteImc76S8Vzwzjj2nC_Yg0BAd9_ps%2Fs1600%2Fpromql-p95-histogram-quantile.png" alt="PromQL p95 graph" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 7 — Connect Grafana to Prometheus
&lt;/h2&gt;

&lt;p&gt;Start Grafana (run the &lt;code&gt;grafana server&lt;/code&gt; binary from the folder you extracted it to) and sign in at &lt;code&gt;http://localhost:3000&lt;/code&gt; (the first-run login is &lt;code&gt;admin&lt;/code&gt; / &lt;code&gt;admin&lt;/code&gt;). Go to &lt;strong&gt;Connections → Data sources → Add data source → Prometheus&lt;/strong&gt;, and set the URL to &lt;code&gt;http://localhost:9090&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fblogger.googleusercontent.com%2Fimg%2Fb%2FR29vZ2xl%2FAVvXsEhpTyoumc9_P1njuJpjmiX30-4O0jFDPWyuGajXfyhRHKj9s_0Ky-pW1Mnp1T0bczRypEXifadoacQgsRyqWn2BNtgwErwn_fhSDF1H-rVYw6ivj_jm_Izqno%2Fs1600%2Fgrafana-prometheus-data-source-form.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fblogger.googleusercontent.com%2Fimg%2Fb%2FR29vZ2xl%2FAVvXsEhpTyoumc9_P1njuJpjmiX30-4O0jFDPWyuGajXfyhRHKj9s_0Ky-pW1Mnp1T0bczRypEXifadoacQgsRyqWn2BNtgwErwn_fhSDF1H-rVYw6ivj_jm_Izqno%2Fs1600%2Fgrafana-prometheus-data-source-form.png" alt="Grafana data source form" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Click &lt;strong&gt;Save &amp;amp; test&lt;/strong&gt;. You want the green confirmation that Grafana successfully queried the Prometheus API — that message is the whole step done:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fblogger.googleusercontent.com%2Fimg%2Fb%2FR29vZ2xl%2FAVvXsEgitlY6GsuBpuxrPX6V2TynybT6LCZ8_ib0NhfO-DL6FozsKqrk2A8mbuWW6MfFlfOoVxntdNc0NWhyASUtrPodjYFwIDXC0l_BUfcXihKT5nHJGGkF24LOHlNKC8v0Ar2qRjOTc2rF3F96rYuQR3XpBZhISpGXj4m8u7sBW5aYCkt_qbjyxyKopldEr8s%2Fs1600%2Fgrafana-data-source-saved-test.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fblogger.googleusercontent.com%2Fimg%2Fb%2FR29vZ2xl%2FAVvXsEgitlY6GsuBpuxrPX6V2TynybT6LCZ8_ib0NhfO-DL6FozsKqrk2A8mbuWW6MfFlfOoVxntdNc0NWhyASUtrPodjYFwIDXC0l_BUfcXihKT5nHJGGkF24LOHlNKC8v0Ar2qRjOTc2rF3F96rYuQR3XpBZhISpGXj4m8u7sBW5aYCkt_qbjyxyKopldEr8s%2Fs1600%2Fgrafana-data-source-saved-test.png" alt="Grafana data source saved and tested" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Running Grafana in Docker instead?&lt;/em&gt; Then &lt;code&gt;localhost&lt;/code&gt; is the container, not your machine — use &lt;code&gt;host.docker.internal&lt;/code&gt; in the URL. This is the single most common reason a first data source fails its test (see Traps).&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 8 — Build the RED dashboard
&lt;/h2&gt;

&lt;p&gt;Create a dashboard with three panels — one per question from Step 6, using the same three queries:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Rate — requests/sec by handler&lt;/strong&gt; (the rate query)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Errors — share of 5xx responses&lt;/strong&gt; (the errors query; set the unit to percent 0–1)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Duration — p95 and p50 by handler&lt;/strong&gt; (the duration query, plus the same query at 0.50)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fmdtywddy70ptgz3dl4ne.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fmdtywddy70ptgz3dl4ne.png" alt="Grafana panel editor" width="800" height="500"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Set the dashboard to refresh every 5 seconds and show the last 15 minutes. Send some gentle traffic to the app and you should see the baseline: about a request a second, a small 5xx share from &lt;code&gt;/boom&lt;/code&gt;, and the Duration panel already telling a story — &lt;code&gt;/slow&lt;/code&gt; sits up near a second while everything else hugs the floor.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fblogger.googleusercontent.com%2Fimg%2Fb%2FR29vZ2xl%2FAVvXsEg-5zFv9Y8D9voVoZAkSL4Fuw6oa8ApzTG8kqlt_Q1lEs1QBPBsCuMc1bX_vdlKYO6Gn4S-YyPr24eaRx3k-lu1sjDL7NZ9M7L3Xz7v_GC_LOUQoxVamKJCO7TQtlG6y0G6D2tL3dRk4-F_5-1nOOUp3A6MnsE4tYPQPIRx6dD-YC5U03G7Sqy3Kwa7CNk%2Fs1600%2Fgrafana-fastapi-red-dashboard.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fblogger.googleusercontent.com%2Fimg%2Fb%2FR29vZ2xl%2FAVvXsEg-5zFv9Y8D9voVoZAkSL4Fuw6oa8ApzTG8kqlt_Q1lEs1QBPBsCuMc1bX_vdlKYO6Gn4S-YyPr24eaRx3k-lu1sjDL7NZ9M7L3Xz7v_GC_LOUQoxVamKJCO7TQtlG6y0G6D2tL3dRk4-F_5-1nOOUp3A6MnsE4tYPQPIRx6dD-YC5U03G7Sqy3Kwa7CNk%2Fs1600%2Fgrafana-fastapi-red-dashboard.png" alt="Grafana RED dashboard" width="800" height="400"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 9 — The burst: watch it catch a slow endpoint live
&lt;/h2&gt;

&lt;p&gt;Now attack your own app. The companion repository's &lt;code&gt;load_burst.py&lt;/code&gt; runs a four-phase load timeline — baseline, an all-endpoints burst, a slow-heavy phase, then an error-heavy phase. The full run made &lt;strong&gt;2,285 requests&lt;/strong&gt;: 1,767 to &lt;code&gt;/&lt;/code&gt;, 344 to &lt;code&gt;/slow&lt;/code&gt;, and 174 to &lt;code&gt;/boom&lt;/code&gt; (every one an HTTP 500).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbr0vfnj9p4iicaoz1yyo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbr0vfnj9p4iicaoz1yyo.png" alt="Dashboard during the burst" width="800" height="500"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;What the dashboard showed, in order:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Rate climbed first&lt;/strong&gt; — peaking at roughly 19 requests per second measured on a 2-minute window. (Your dashboard's 5-minute window will show a lower peak, around 6 req/s. Both are correct — a rate is meaningless without its window, which is why this post states the window every time.)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Errors followed&lt;/strong&gt; — at the peak of the error-heavy phase, &lt;strong&gt;over 11% of responses were failing&lt;/strong&gt; (11.4% measured).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Duration is the tell.&lt;/strong&gt; &lt;code&gt;/slow&lt;/code&gt;'s p95 read &lt;strong&gt;0.975 seconds&lt;/strong&gt; — and it had read that since the very first scrape, long before the burst, because the endpoint sleeps 0.8 seconds and the histogram interpolates inside its 0.5–1.0 bucket. The dashboard did not just catch the burst; it had already fingered the slow endpoint at baseline. (The overall p95 across all endpoints peaked at about &lt;strong&gt;0.90 seconds&lt;/strong&gt; during the burst — remember that number when we set the alert threshold in Step 10.)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ffxfj2sq8vmlqhh7dfeab.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ffxfj2sq8vmlqhh7dfeab.png" alt="5xx share at the peak" width="800" height="500"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Step 10 — One alert: know when it happens again
&lt;/h2&gt;

&lt;p&gt;A dashboard you must watch is a chore; an alert watches for you. In Grafana: &lt;strong&gt;Alerting → Alert rules → New alert rule&lt;/strong&gt;. Query the &lt;em&gt;overall&lt;/em&gt; p95 (the duration query without the per-handler split), and set the condition: when the last value of that query &lt;strong&gt;is above 0.5&lt;/strong&gt;, sustained for &lt;strong&gt;1 minute&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ftdk8fst0shb8j3xmxoax.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ftdk8fst0shb8j3xmxoax.png" alt="Grafana alert rule" width="800" height="500"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Run the burst again and wait. Once the p95 stays above half a second for a full minute, the rule flips to &lt;strong&gt;Firing&lt;/strong&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F6y5m9b4958yk7k4qnft0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F6y5m9b4958yk7k4qnft0.png" alt="Alert firing" width="800" height="500"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Two honest notes. First, this demo wires &lt;strong&gt;no notification channel&lt;/strong&gt; — the rule fires in Grafana's UI, and connecting email, Slack or a webhook (a "contact point") is your next step; this post does not claim a message was delivered. Second, the same rule exists as a Prometheus alerting rule in YAML in the companion repository, for setups that alert from Prometheus instead of Grafana.&lt;/p&gt;

&lt;h2&gt;
  
  
  Traps (each one cost somebody an hour)
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Target DOWN.&lt;/strong&gt; If Prometheus shows your target as DOWN, nothing else can work. Usually the app is not running, or the port in &lt;code&gt;prometheus.yml&lt;/code&gt; is wrong. Check Targets &lt;em&gt;before&lt;/em&gt; debugging queries.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Docker networking.&lt;/strong&gt; If Grafana runs in Docker and Prometheus (or the app) runs on your host, &lt;code&gt;localhost&lt;/code&gt; inside the data-source URL points at the container. Use &lt;code&gt;host.docker.internal&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Querying &lt;code&gt;status="500"&lt;/code&gt;.&lt;/strong&gt; It returns an empty result — not an error, just nothing — because the instrumentator groups statuses (&lt;code&gt;5xx&lt;/code&gt;). An empty graph here almost always means a label value that does not exist, not "no errors".&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdwe9g6v0ezh58fsdng6b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdwe9g6v0ezh58fsdng6b.png" alt="status=500 returns an empty result" width="800" height="500"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Recap
&lt;/h2&gt;

&lt;p&gt;You now have the full loop: the app publishes its own numbers at &lt;code&gt;/metrics&lt;/code&gt; (two calls to add), Prometheus scrapes them every few seconds, three PromQL queries answer Rate, Errors and Duration, a Grafana dashboard shows them live, and one alert fires when the p95 stays too high. The pattern transfers unchanged to a real application: keep the three questions, watch the labels (grouped statuses!), and always quote a rate with its window.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Practice task:&lt;/strong&gt; add the instrumentator to an app of your own, find your slowest endpoint's p95 at baseline, and write the number down. If it surprises you, the dashboard has already paid for itself.&lt;/p&gt;

&lt;h2&gt;
  
  
  FAQ
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Do I need Docker for Prometheus and Grafana?&lt;/strong&gt;&lt;br&gt;
No. Both are single binaries that run locally, which is how this tutorial was produced. Docker works too — just mind the &lt;code&gt;host.docker.internal&lt;/code&gt; note in Step 7.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why is my p95 an estimate?&lt;/strong&gt;&lt;br&gt;
Because it comes from a histogram: Prometheus knows how many requests fell into each duration bucket, and &lt;code&gt;histogram_quantile&lt;/code&gt; interpolates inside the bucket. It is the right tool for spotting slow endpoints, not a stopwatch.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What does this cost to run in production?&lt;/strong&gt;&lt;br&gt;
Prometheus and Grafana OSS are free and self-hosted. The real cost is storage, which you control with the scrape interval and retention settings — start at 15–60 second scrapes, not the 5 seconds this demo used.&lt;/p&gt;

&lt;h2&gt;
  
  
  Sources
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://pypi.org/project/prometheus-fastapi-instrumentator/" rel="noopener noreferrer"&gt;prometheus-fastapi-instrumentator — PyPI project page&lt;/a&gt; (the instrumentator's defaults and label behaviour)&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://prometheus.io/docs/prometheus/latest/querying/basics/" rel="noopener noreferrer"&gt;Prometheus — Querying basics&lt;/a&gt; (rate, histogram_quantile, label matchers)&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://grafana.com/docs/grafana/latest/alerting/" rel="noopener noreferrer"&gt;Grafana — Alerting documentation&lt;/a&gt; (alert rules, conditions, pending/firing states)&lt;/li&gt;
&lt;li&gt;All measurements in this post (request counts, rates, percentiles, the firing alert) are from the author's own run of the companion code, November 2026.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;This post was originally published on &lt;a href="https://visualstudiolearn.blogspot.com/2026/11/monitor-fastapi-app-with-prometheus.html" rel="noopener noreferrer"&gt;Visual Studio Learn&lt;/a&gt;, where the video version and the free companion code are linked.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>fastapi</category>
      <category>prometheus</category>
      <category>grafana</category>
      <category>python</category>
    </item>
    <item>
      <title>How Do I Backup and Restore a SQL Server Database in SSMS? (Step by Step, 2026)</title>
      <dc:creator>Visual Studio Learn</dc:creator>
      <pubDate>Thu, 05 Nov 2026 22:45:00 +0000</pubDate>
      <link>https://dev.to/visualstudiolearn/how-do-i-backup-and-restore-a-sql-server-database-in-ssms-step-by-step-2026-1p60</link>
      <guid>https://dev.to/visualstudiolearn/how-do-i-backup-and-restore-a-sql-server-database-in-ssms-step-by-step-2026-1p60</guid>
      <description>&lt;p&gt;Back up a SQL Server database in SSMS to a &lt;code&gt;.bak&lt;/code&gt; file, break it, then restore it back — that is this whole post, in that order. We take a &lt;strong&gt;full backup&lt;/strong&gt; of the DemoDb database from the &lt;a href="https://visualstudiolearn.blogspot.com/2026/11/how-do-i-connect-sql-server-to-visual.html" rel="noopener noreferrer"&gt;previous tutorial&lt;/a&gt;, delete a row and corrupt another one on purpose, then restore the backup &lt;strong&gt;over the damage&lt;/strong&gt; and prove the data is back. After that we restore the same file a second time &lt;strong&gt;as a copy&lt;/strong&gt;, side by side with the original. Every step has its own real screenshot, and the two restore failures we hit on the way — the ones you will hit too — are shown exactly as they appeared, with their fixes.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Versions used in this tutorial&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;SQL Server &lt;strong&gt;2025 (17.x)&lt;/strong&gt; — Enterprise Developer edition (free for development and testing), build 17.0.1000.7&lt;/li&gt;
&lt;li&gt;SQL Server Management Studio &lt;strong&gt;22.11.3&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Demo database: &lt;strong&gt;DemoDb&lt;/strong&gt; with the table &lt;strong&gt;dbo.DemoCustomers&lt;/strong&gt; — the same database the previous post connected to Visual Studio&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;

&lt;p&gt;The screenshots were captured on a Windows Server 2022 machine; the SSMS clicks are identical on Windows 10 and 11 desktops.&lt;/p&gt;

&lt;h2&gt;
  
  
  Before you start: set up your environment from zero
&lt;/h2&gt;

&lt;p&gt;Nothing here assumes a running server. If you worked through the previous post, you already have all of this — skip to the verify step.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step A — Install SQL Server 2025 (Enterprise Developer, free)
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;On Microsoft's SQL Server downloads page, choose &lt;strong&gt;Developer → Enterprise Developer&lt;/strong&gt;. New in SQL Server 2025, there are two free Developer editions: &lt;strong&gt;Enterprise Developer&lt;/strong&gt; (every Enterprise feature) and &lt;strong&gt;Standard Developer&lt;/strong&gt; (every Standard feature). Both are free — no key, no subscription — licensed for development and testing, never production.&lt;/li&gt;
&lt;li&gt;Run setup → &lt;strong&gt;Installation → New SQL Server standalone installation&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;At &lt;strong&gt;Instance Configuration&lt;/strong&gt;, keep the &lt;strong&gt;default instance&lt;/strong&gt; (this tutorial uses a default instance; a named instance works the same, you just type its name when connecting).&lt;/li&gt;
&lt;li&gt;At &lt;strong&gt;Database Engine Configuration → Authentication Mode&lt;/strong&gt;, keep &lt;strong&gt;Windows authentication mode&lt;/strong&gt; — it is all this tutorial needs.&lt;/li&gt;
&lt;li&gt;Click &lt;strong&gt;Add Current User&lt;/strong&gt; so your Windows account is a SQL Server administrator, then &lt;strong&gt;Install&lt;/strong&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Step B — Install SSMS 22
&lt;/h3&gt;

&lt;p&gt;Download &lt;strong&gt;SQL Server Management Studio 22&lt;/strong&gt; (this tutorial uses 22.11.3) from Microsoft — a separate free tool — and install it. Backup and restore live in SSMS, not in Visual Studio; administering the server is SSMS's job.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step C — Create the backup folder and the demo database
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Create a folder for backups: &lt;code&gt;C:\VSL-Backups&lt;/code&gt;. One honest warning that saves confusion later: when a backup runs, it is the &lt;strong&gt;SQL Server service account&lt;/strong&gt; — not your Windows login — that reads and writes this folder. On a default local install that just works; if a backup ever fails with an access-denied error, it is the service account's permission that is missing (see Errors #5).&lt;/li&gt;
&lt;li&gt;Open SSMS, connect to your instance, open a &lt;strong&gt;New Query&lt;/strong&gt; window and run &lt;code&gt;setup.sql&lt;/code&gt; from the companion code folder (linked at the end):
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt; &lt;span class="k"&gt;DATABASE&lt;/span&gt; &lt;span class="n"&gt;DemoDb&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;GO&lt;/span&gt;
&lt;span class="n"&gt;USE&lt;/span&gt; &lt;span class="n"&gt;DemoDb&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;GO&lt;/span&gt;
&lt;span class="k"&gt;CREATE&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="n"&gt;dbo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;DemoCustomers&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;CustomerId&lt;/span&gt; &lt;span class="nb"&gt;INT&lt;/span&gt; &lt;span class="k"&gt;IDENTITY&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;PRIMARY&lt;/span&gt; &lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;FullName&lt;/span&gt; &lt;span class="n"&gt;NVARCHAR&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;NOT&lt;/span&gt; &lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;City&lt;/span&gt; &lt;span class="n"&gt;NVARCHAR&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;NOT&lt;/span&gt; &lt;span class="k"&gt;NULL&lt;/span&gt;
&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="k"&gt;INSERT&lt;/span&gt; &lt;span class="k"&gt;INTO&lt;/span&gt; &lt;span class="n"&gt;dbo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;DemoCustomers&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;FullName&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;City&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;VALUES&lt;/span&gt;
&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="s1"&gt;'Amara'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="s1"&gt;'Toronto'&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="s1"&gt;'Jonas'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="s1"&gt;'Berlin'&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="s1"&gt;'Priya'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="s1"&gt;'Lagos'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="n"&gt;CustomerId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;FullName&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;City&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;dbo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;DemoCustomers&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step D — Verify everything
&lt;/h3&gt;

&lt;p&gt;Two checks. First, the setup script's SELECT returns three rows — Amara in Toronto, Jonas in Berlin, Priya in Lagos. That grid is the &lt;em&gt;before&lt;/em&gt; picture; the whole tutorial is about getting back to exactly it.&lt;/p&gt;

&lt;p&gt;Second, check the database's &lt;strong&gt;recovery model&lt;/strong&gt; — one setting that decides whether a checkbox in Step 13 even exists:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;recovery_model_desc&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;sys&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;databases&lt;/span&gt; &lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'DemoDb'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;On a default install this returns &lt;strong&gt;FULL&lt;/strong&gt;, because new databases inherit their recovery model from the &lt;strong&gt;model&lt;/strong&gt; system database, and model ships as FULL. DemoDb here is FULL. If yours says SIMPLE, everything in this post still works except the tail-log part of Step 13 — under SIMPLE that section is not offered at all, and there is nothing to uncheck. Now the backup.&lt;/p&gt;

&lt;h2&gt;
  
  
  Part A — Take the full backup (Steps 1–7)
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Step 1 — Connect, and find DemoDb in the tree
&lt;/h3&gt;

&lt;p&gt;Open SSMS and connect to your instance. On this machine the server name is &lt;code&gt;localhost&lt;/code&gt; (a default instance on the same PC), with &lt;strong&gt;Windows Authentication&lt;/strong&gt;. SSMS 22's Connect dialog sets &lt;strong&gt;Encrypt&lt;/strong&gt; to Mandatory — and on a local instance you will typically tick &lt;strong&gt;Trust Server Certificate&lt;/strong&gt;, the same self-signed-certificate story as the previous post's Visual Studio error.&lt;/p&gt;

&lt;p&gt;Expand &lt;strong&gt;Databases&lt;/strong&gt; and find &lt;strong&gt;DemoDb → Tables → dbo.DemoCustomers&lt;/strong&gt;. If the table is there, your setup is real and Part A can start.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 2 — Right-click DemoDb → Tasks → Back Up…
&lt;/h3&gt;

&lt;p&gt;Backups start from the database itself. Right-click &lt;strong&gt;DemoDb&lt;/strong&gt;, hover &lt;strong&gt;Tasks&lt;/strong&gt;, and click &lt;strong&gt;Back Up…&lt;/strong&gt; — the first item in the Tasks submenu.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 3 — Read the Back Up Database dialog once, properly
&lt;/h3&gt;

&lt;p&gt;The dialog opens on its &lt;strong&gt;General&lt;/strong&gt; page, and four fields decide everything:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Database:&lt;/strong&gt; DemoDb (the database you right-clicked).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Recovery model:&lt;/strong&gt; FULL — read-only here; it is the setting you checked in Step D.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Backup type:&lt;/strong&gt; &lt;strong&gt;Full&lt;/strong&gt;. A full backup copies the entire database. The other types — differential and transaction log — only make sense standing on a full backup, which is why we take this one first.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Backup component:&lt;/strong&gt; &lt;strong&gt;Database&lt;/strong&gt; (whole database, not selected files).&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Step 4 — Set the destination: your own folder, your own file name
&lt;/h3&gt;

&lt;p&gt;Under &lt;strong&gt;Destination&lt;/strong&gt;, SSMS pre-fills a backup file inside the instance's own Backup folder. Remove it. Click &lt;strong&gt;Add…&lt;/strong&gt;, and in &lt;strong&gt;Select Backup Destination&lt;/strong&gt; type the full path of &lt;em&gt;your&lt;/em&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;C&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="err"&gt;\&lt;/span&gt;&lt;span class="n"&gt;VSL&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="n"&gt;Backups&lt;/span&gt;&lt;span class="err"&gt;\&lt;/span&gt;&lt;span class="n"&gt;DemoDb&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="k"&gt;full&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;2026&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;11&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="mi"&gt;05&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;bak&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;.bak&lt;/code&gt; extension is a convention, not a rule the engine enforces — but every tool and every colleague expects it, and the dialog itself tells you to use it. A dated file name pays off the first time a folder holds more than one backup.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 5 — Optional but worth it once: press Script and read what the dialog really does
&lt;/h3&gt;

&lt;p&gt;Before clicking OK, try the &lt;strong&gt;Script&lt;/strong&gt; button at the top of the dialog (Script → Script Action to New Query Window). SSMS writes the exact T-SQL your clicks amount to, into a query window:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="n"&gt;BACKUP&lt;/span&gt; &lt;span class="k"&gt;DATABASE&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;DemoDb&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="k"&gt;TO&lt;/span&gt; &lt;span class="n"&gt;DISK&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="s1"&gt;'C:&lt;/span&gt;&lt;span class="se"&gt;\V&lt;/span&gt;&lt;span class="s1"&gt;SL-Backups&lt;/span&gt;&lt;span class="se"&gt;\D&lt;/span&gt;&lt;span class="s1"&gt;emoDb-full-2026-11-05.bak'&lt;/span&gt;
&lt;span class="k"&gt;WITH&lt;/span&gt; &lt;span class="n"&gt;NOFORMAT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;NOINIT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;NAME&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="s1"&gt;'DemoDb-Full Database Backup'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;SKIP&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;NOREWIND&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;NOUNLOAD&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;STATS&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Two options in that statement matter for later. &lt;strong&gt;NOINIT&lt;/strong&gt; means &lt;em&gt;append&lt;/em&gt;: if the file already exists, the new backup is added to it as another backup &lt;em&gt;set&lt;/em&gt; rather than replacing it. The opposite choice — starting a fresh media set — is the &lt;strong&gt;Overwrite all existing backup sets&lt;/strong&gt; option on the dialog's Media Options page (FORMAT in T-SQL). Appending is the default and it surprises people at restore time (Errors #8). The companion folder's &lt;code&gt;01-backup-full.sql&lt;/code&gt; is this statement, plus an optional &lt;code&gt;RESTORE VERIFYONLY&lt;/code&gt; line that checks the finished backup set is complete and readable.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 6 — Click OK and read the confirmation
&lt;/h3&gt;

&lt;p&gt;Close the extra query window if you opened one, click &lt;strong&gt;OK&lt;/strong&gt; on the Back Up Database dialog, and wait for the confirmation:&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 7 — Prove the file exists, on disk, with a size
&lt;/h3&gt;

&lt;p&gt;Open &lt;code&gt;C:\VSL-Backups&lt;/code&gt; in File Explorer. The &lt;code&gt;.bak&lt;/code&gt; file is there — on this machine &lt;strong&gt;3,636 KB&lt;/strong&gt;, written at the minute the dialog confirmed. A backup you have not seen on disk is a rumour; this one is a file.&lt;/p&gt;

&lt;h2&gt;
  
  
  Part B — Break the database, on purpose (Step 8)
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Step 8 — One wrong UPDATE, one DELETE
&lt;/h3&gt;

&lt;p&gt;A restore you have never watched fix real damage is a restore you merely believe in. So we do the damage deliberately — the two accidents that happen in production every week: a value overwritten with a wrong one, and a row deleted outright. In a new query window on DemoDb, run &lt;code&gt;02-break-it.sql&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="n"&gt;USE&lt;/span&gt; &lt;span class="n"&gt;DemoDb&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;UPDATE&lt;/span&gt; &lt;span class="n"&gt;dbo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;DemoCustomers&lt;/span&gt; &lt;span class="k"&gt;SET&lt;/span&gt; &lt;span class="n"&gt;City&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="s1"&gt;'Munich'&lt;/span&gt; &lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;FullName&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="s1"&gt;'Jonas'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;DELETE&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;dbo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;DemoCustomers&lt;/span&gt; &lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;FullName&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="s1"&gt;'Priya'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="n"&gt;CustomerId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;FullName&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;City&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;dbo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;DemoCustomers&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The SELECT now returns exactly &lt;strong&gt;2 rows&lt;/strong&gt;: Amara untouched, and Jonas — in &lt;strong&gt;Munich&lt;/strong&gt;, a city he was never in. Priya's row is gone. Keep this query window open; in about two steps it becomes the villain of the piece.&lt;/p&gt;

&lt;h2&gt;
  
  
  Part C — Restore over the damage (Steps 9–15)
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Step 9 — Start from the Databases node, not from the database
&lt;/h3&gt;

&lt;p&gt;Here is the classic wrong turn, made by almost everyone the first time: restore does &lt;strong&gt;not&lt;/strong&gt; start by right-clicking the database. Right-click the &lt;strong&gt;Databases&lt;/strong&gt; node — the folder above all your databases — and choose &lt;strong&gt;Restore Database…&lt;/strong&gt;. Starting at the node is what allows restoring over an existing database &lt;em&gt;and&lt;/em&gt; restoring under a brand-new name (Part D) from the same dialog.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 10 — Source: Device → add your .bak file
&lt;/h3&gt;

&lt;p&gt;On the &lt;strong&gt;General&lt;/strong&gt; page, under &lt;strong&gt;Source&lt;/strong&gt;, select &lt;strong&gt;Device&lt;/strong&gt; (not Database), click the &lt;strong&gt;…&lt;/strong&gt; button, and in &lt;strong&gt;Select backup devices&lt;/strong&gt; click &lt;strong&gt;Add&lt;/strong&gt;. Browse to &lt;code&gt;C:\VSL-Backups\DemoDb-full-2026-11-05.bak&lt;/code&gt; and OK your way back. The devices dialog now lists your file as the backup media — the restore will read its sets from here.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 11 — Check the destination and the backup set
&lt;/h3&gt;

&lt;p&gt;Back on the General page, SSMS has read the file and filled in the plan:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Source Database:&lt;/strong&gt; DemoDb (read from the backup itself).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Destination Database:&lt;/strong&gt; &lt;strong&gt;DemoDb&lt;/strong&gt; — the existing, damaged database. This one field is the whole difference between restoring &lt;em&gt;over&lt;/em&gt; a database and restoring &lt;em&gt;as a copy&lt;/em&gt;: type a different name here and Part D happens instead.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Backup sets to restore:&lt;/strong&gt; one row — &lt;em&gt;DemoDb-Full Database Backup&lt;/em&gt;, type Full — ticked. If this grid ever shows more rows than you expect, stop and read Errors #8 before clicking anything.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Note the yellow banner at the top of the dialog: &lt;em&gt;“A tail-log backup of the source database will be taken. View this setting on the Options page.”&lt;/em&gt; SSMS is warning you about Step 13 already. Good — we will deal with it there, deliberately.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 12 — Files page: where the restored files will live
&lt;/h3&gt;

&lt;p&gt;Open the &lt;strong&gt;Files&lt;/strong&gt; page and read the grid, even if you change nothing. Each row is one file inside the backup: its &lt;strong&gt;logical name&lt;/strong&gt; (&lt;code&gt;DemoDb&lt;/code&gt; for the data file, &lt;code&gt;DemoDb_log&lt;/code&gt; for the log), where it originally lived, and &lt;strong&gt;Restore As&lt;/strong&gt; — where it will be written. For a restore over itself, Restore As points at the database's current files, which is exactly right. This grid is also the T-SQL &lt;code&gt;WITH MOVE&lt;/code&gt; clause wearing a dialog's clothes — Part D edits it, and Errors #4 is what happens when the paths point somewhere that does not exist.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 13 — Options page: the three switches this whole tutorial turns on
&lt;/h3&gt;

&lt;p&gt;Open the &lt;strong&gt;Options&lt;/strong&gt; page. As the dialog first opens it — and this is verified on the screenshots from this tutorial's own session — the page arrives like this: &lt;strong&gt;Overwrite&lt;/strong&gt; unticked, &lt;strong&gt;Close existing connections&lt;/strong&gt; unticked, and &lt;strong&gt;Take tail-log backup before restore&lt;/strong&gt; &lt;em&gt;ticked&lt;/em&gt;. All three defaults are wrong for what we are doing. Set them deliberately:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Overwrite the existing database (WITH REPLACE): TICK it.&lt;/strong&gt; You are knowingly replacing DemoDb's current contents with the backup's. The T-SQL name tells the truth: REPLACE bypasses SQL Server's built-in safety checks, so it should only ever be ticked when overwriting is the actual intention — here, it is.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Close existing connections to destination database: TICK it.&lt;/strong&gt; A restore needs the database to itself. Any open connection — an application, another SSMS window, &lt;em&gt;the Step 8 window still sitting on DemoDb&lt;/em&gt; — blocks it. Ticking this makes SSMS flip the database to single-user, restore, and flip it back to multi-user for you.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Take tail-log backup before restore: UNTICK it.&lt;/strong&gt; A &lt;em&gt;tail-log backup&lt;/em&gt; captures the log records written since the last backup — the tool for rolling a database &lt;em&gt;forward&lt;/em&gt; to the latest possible moment before a restore. We are doing the opposite: travelling &lt;em&gt;back&lt;/em&gt; to the backup, throwing the later changes (our damage) away. A tail-log backup here is not just pointless — on a restore under a new name it can flip the &lt;em&gt;original&lt;/em&gt; database into the Restoring state (Errors #3). Leave &lt;strong&gt;Recovery state&lt;/strong&gt; at its default, &lt;strong&gt;RESTORE WITH RECOVERY&lt;/strong&gt; — it brings the database back online, ready to use, when the restore finishes.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  What actually went wrong twice, before this restore worked
&lt;/h3&gt;

&lt;p&gt;This tutorial's own session hit the restore failure twice before the clean run above — same error both times, two different causes. Both dialogs are real, captured live, and they are the two failures you are most likely to meet:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Attempt 1 — Overwrite unticked.&lt;/strong&gt; We expected the textbook safety error here (error 3154 — see Errors #1). We never reached it. The restore failed earlier, with &lt;strong&gt;“Exclusive access could not be obtained because the database is in use”&lt;/strong&gt; — because the Step 8 query window was still connected to DemoDb. Lesson: the in-use check fires &lt;em&gt;before&lt;/em&gt; the overwrite safety check. An open window beats a checkbox.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Attempt 2 — Overwrite ticked, Close existing connections unticked.&lt;/strong&gt; Same error, verbatim. With Overwrite now on, the only remaining blocker was the connection itself. (Notice, in the full session, that the tail-log backup was also still ticked at this point — three wrong switches, peeled off one at a time.) The fix for both attempts is the Step 13 setting above: &lt;strong&gt;Close existing connections&lt;/strong&gt;. Switching your own query window's context to &lt;code&gt;master&lt;/code&gt; first — &lt;code&gt;USE master;&lt;/code&gt; — helps too; the session did both before the clean run.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 14 — Click OK: restored successfully
&lt;/h3&gt;

&lt;p&gt;With the three switches set, click &lt;strong&gt;OK&lt;/strong&gt;. The restore runs (a small database is seconds) and SSMS confirms:&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 15 — The restore-proof: three rows, and Jonas back in Berlin
&lt;/h3&gt;

&lt;p&gt;Never trust the success dialog alone — verify the data. Run &lt;code&gt;05-verify.sql&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="n"&gt;USE&lt;/span&gt; &lt;span class="n"&gt;DemoDb&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="n"&gt;CustomerId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;FullName&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;City&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;dbo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;DemoCustomers&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Three rows.&lt;/strong&gt; And check the &lt;em&gt;value&lt;/em&gt;, not just the count: &lt;strong&gt;Jonas is back in Berlin&lt;/strong&gt;, and Priya's row exists again. The restore did not just bring back a row count — it rolled the database back to the exact moment the backup was taken, undoing an UPDATE and a DELETE in one move. If your grid ever shows three rows but Jonas still in Munich, you restored the wrong backup set — Errors #8.&lt;/p&gt;

&lt;h2&gt;
  
  
  Part D — Restore the same backup as a copy (Steps 16–18)
&lt;/h2&gt;

&lt;p&gt;Same file, different destination: a second, independent database next to the original. This is how you inspect a backup without touching production data, hand a developer a realistic copy, or park a before-snapshot next to a risky change.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 16 — Repeat Steps 9–11, but type a new name: DemoDbCopy
&lt;/h3&gt;

&lt;p&gt;Right-click &lt;strong&gt;Databases → Restore Database…&lt;/strong&gt;, Source &lt;strong&gt;Device&lt;/strong&gt;, add the same &lt;code&gt;.bak&lt;/code&gt; — then on the General page, change &lt;strong&gt;Destination Database&lt;/strong&gt; from DemoDb to &lt;strong&gt;DemoDbCopy&lt;/strong&gt;. Typing a name that does not exist yet is the entire trick; watch the dialog's title change to match.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 17 — Files page: rename the Restore As paths
&lt;/h3&gt;

&lt;p&gt;Open the &lt;strong&gt;Files&lt;/strong&gt; page before clicking anything else. The backup's files want to land on the original database's file names — &lt;code&gt;DemoDb.mdf&lt;/code&gt; and &lt;code&gt;DemoDb_log.ldf&lt;/code&gt;, which are in use. Rename &lt;strong&gt;Restore As&lt;/strong&gt; for both rows, keeping the same folder:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="err"&gt;\&lt;/span&gt;&lt;span class="n"&gt;MSSQL&lt;/span&gt;&lt;span class="err"&gt;\&lt;/span&gt;&lt;span class="k"&gt;DATA&lt;/span&gt;&lt;span class="err"&gt;\&lt;/span&gt;&lt;span class="n"&gt;DemoDbCopy&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;mdf&lt;/span&gt;
&lt;span class="p"&gt;...&lt;/span&gt;&lt;span class="err"&gt;\&lt;/span&gt;&lt;span class="n"&gt;MSSQL&lt;/span&gt;&lt;span class="err"&gt;\&lt;/span&gt;&lt;span class="k"&gt;DATA&lt;/span&gt;&lt;span class="err"&gt;\&lt;/span&gt;&lt;span class="n"&gt;DemoDbCopy_log&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;ldf&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then open the &lt;strong&gt;Options&lt;/strong&gt; page and &lt;strong&gt;untick Take tail-log backup&lt;/strong&gt; here as well — for a restore under a new name this is the dangerous one (Errors #3). Overwrite stays unticked: DemoDbCopy does not exist, so there is nothing to overwrite, and SSMS does not ask for it.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 18 — Click OK, then look at the tree
&lt;/h3&gt;

&lt;p&gt;Click &lt;strong&gt;OK&lt;/strong&gt;. When it completes, refresh &lt;strong&gt;Databases&lt;/strong&gt; in Object Explorer: &lt;strong&gt;DemoDb and DemoDbCopy&lt;/strong&gt;, side by side. Open a query window on &lt;strong&gt;DemoDbCopy&lt;/strong&gt; and run the same SELECT: the same three rows, in the copy — while the original was never touched by this second restore.&lt;/p&gt;

&lt;p&gt;The T-SQL form of Part D (in &lt;code&gt;04-restore-as-copy.sql&lt;/code&gt;) shows what the Files page edits became — note the logical names, straight from Step 12's grid:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="n"&gt;RESTORE&lt;/span&gt; &lt;span class="k"&gt;DATABASE&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="n"&gt;DemoDbCopy&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;DISK&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="s1"&gt;'C:&lt;/span&gt;&lt;span class="se"&gt;\V&lt;/span&gt;&lt;span class="s1"&gt;SL-Backups&lt;/span&gt;&lt;span class="se"&gt;\D&lt;/span&gt;&lt;span class="s1"&gt;emoDb-full-2026-11-05.bak'&lt;/span&gt;
&lt;span class="k"&gt;WITH&lt;/span&gt;
    &lt;span class="k"&gt;MOVE&lt;/span&gt; &lt;span class="s1"&gt;'DemoDb'&lt;/span&gt;     &lt;span class="k"&gt;TO&lt;/span&gt; &lt;span class="s1"&gt;'C:&lt;/span&gt;&lt;span class="se"&gt;\P&lt;/span&gt;&lt;span class="s1"&gt;rogram Files&lt;/span&gt;&lt;span class="se"&gt;\M&lt;/span&gt;&lt;span class="s1"&gt;icrosoft SQL Server&lt;/span&gt;&lt;span class="se"&gt;\M&lt;/span&gt;&lt;span class="s1"&gt;SSQL17.MSSQLSERVER&lt;/span&gt;&lt;span class="se"&gt;\M&lt;/span&gt;&lt;span class="s1"&gt;SSQL&lt;/span&gt;&lt;span class="se"&gt;\D&lt;/span&gt;&lt;span class="s1"&gt;ATA&lt;/span&gt;&lt;span class="se"&gt;\D&lt;/span&gt;&lt;span class="s1"&gt;emoDbCopy.mdf'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="k"&gt;MOVE&lt;/span&gt; &lt;span class="s1"&gt;'DemoDb_log'&lt;/span&gt; &lt;span class="k"&gt;TO&lt;/span&gt; &lt;span class="s1"&gt;'C:&lt;/span&gt;&lt;span class="se"&gt;\P&lt;/span&gt;&lt;span class="s1"&gt;rogram Files&lt;/span&gt;&lt;span class="se"&gt;\M&lt;/span&gt;&lt;span class="s1"&gt;icrosoft SQL Server&lt;/span&gt;&lt;span class="se"&gt;\M&lt;/span&gt;&lt;span class="s1"&gt;SSQL17.MSSQLSERVER&lt;/span&gt;&lt;span class="se"&gt;\M&lt;/span&gt;&lt;span class="s1"&gt;SSQL&lt;/span&gt;&lt;span class="se"&gt;\D&lt;/span&gt;&lt;span class="s1"&gt;ATA&lt;/span&gt;&lt;span class="se"&gt;\D&lt;/span&gt;&lt;span class="s1"&gt;emoDbCopy_log.ldf'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;RECOVERY&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Backup types and recovery models, in one minute
&lt;/h2&gt;

&lt;p&gt;Everything above was one &lt;strong&gt;full backup&lt;/strong&gt; — the whole database in one file, the foundation every other backup type stands on. The other two, now that a full backup exists:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Differential backup&lt;/strong&gt; — only the changes since the last full backup. Restoring means the latest full &lt;em&gt;plus&lt;/em&gt; the single latest differential — never a chain of them.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Transaction log backup&lt;/strong&gt; — the log records since the last log backup; a chain of them is what makes point-in-time restore possible. Available only under the &lt;strong&gt;FULL&lt;/strong&gt; or &lt;strong&gt;BULK_LOGGED&lt;/strong&gt; recovery models — under &lt;strong&gt;SIMPLE&lt;/strong&gt;, the log is truncated automatically and log backups do not exist, which is also why the tail-log section vanishes from the Options page.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Choosing a recovery model is choosing how much work you can afford to lose: SIMPLE trades recoverability for zero log management; FULL keeps every log record so you can restore to a point in time, at the price of taking log backups so the log does not grow forever. And the one-line habit that outranks all of this: &lt;strong&gt;a backup is not a backup until you have restored it once&lt;/strong&gt; — which, if you followed along, you have now done twice.&lt;/p&gt;

&lt;h2&gt;
  
  
  Errors you may hit
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. Error 3154 — “The backup set holds a backup of a database other than the existing 'DemoDb' database”
&lt;/h3&gt;

&lt;p&gt;The safety check doing its job: you are restoring over an existing database &lt;em&gt;without&lt;/em&gt; Overwrite (WITH REPLACE), and SQL Server refuses to silently replace one database with another's backup. The full dialog form, from Microsoft's own SSMS documentation example, reads: &lt;em&gt;“System.Data.SqlClient.SqlError: The backup set holds a backup of a database other than the existing 'Sales' database. (Microsoft.SqlServer.SmoExtended)”&lt;/em&gt; — with your database's name in place of Sales. &lt;strong&gt;Fix:&lt;/strong&gt; if overwriting is genuinely the intention, tick &lt;strong&gt;Overwrite the existing database (WITH REPLACE)&lt;/strong&gt; on the Options page. If it is not the intention, stop — this error just saved you. (One sequencing truth from this tutorial's session: if anything is still &lt;em&gt;connected&lt;/em&gt; to the database, you will meet Error #2 first — the in-use check fires earlier.)&lt;/p&gt;

&lt;h3&gt;
  
  
  2. “Exclusive access could not be obtained because the database is in use”
&lt;/h3&gt;

&lt;p&gt;The error this tutorial actually hit — twice, in the Part C callout above. A restore needs exclusive access; &lt;em&gt;something&lt;/em&gt; is connected: an application, a service, or your own SSMS query window still pointed at the database (guilty). &lt;strong&gt;Fix:&lt;/strong&gt; tick &lt;strong&gt;Close existing connections to destination database&lt;/strong&gt; on the Options page — SSMS flips the database to single-user, restores, and returns it to multi-user — and switch your own query windows to &lt;code&gt;master&lt;/code&gt; (&lt;code&gt;USE master;&lt;/code&gt;) before restoring. The T-SQL equivalent of the checkbox is in &lt;code&gt;03-restore-overwrite.sql&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. The tail-log trap — two faces
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Face one:&lt;/strong&gt; you are restoring to go &lt;em&gt;back&lt;/em&gt; to a backup (our Part C), and &lt;strong&gt;Take tail-log backup before restore&lt;/strong&gt; is ticked — as it is by default under the FULL recovery model. The tail-log backup preserves the very changes you are trying to undo, and if its file cannot be written, the restore fails before it starts. Untick it when travelling back. &lt;strong&gt;Face two (the dangerous one):&lt;/strong&gt; restoring under a &lt;em&gt;new name&lt;/em&gt; with the tail-log option left on can leave the &lt;em&gt;original&lt;/em&gt; database stuck in the &lt;strong&gt;Restoring&lt;/strong&gt; state — Microsoft's restore documentation walks through exactly this scenario, including the “the tail of the log for the database has not been backed up” error that accompanies it. Untick it in Part D as well. The rule that covers both: a tail-log backup belongs to rolling &lt;em&gt;forward&lt;/em&gt; before a restore, never to going back or sideways.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. Restore As paths point at a folder that does not exist
&lt;/h3&gt;

&lt;p&gt;The Files page's &lt;strong&gt;Restore As&lt;/strong&gt; values come from where the files lived on the machine that &lt;em&gt;made&lt;/em&gt; the backup. Restore a backup from another server — or rename carelessly in Part D — and the paths can point at folders that are not on this machine, and the restore fails on file creation. &lt;strong&gt;Fix:&lt;/strong&gt; correct the paths on the Files page (or use &lt;code&gt;WITH MOVE&lt;/code&gt; in T-SQL, exactly as &lt;code&gt;04-restore-as-copy.sql&lt;/code&gt; does). Also make sure the new file names do not collide with an existing database's files.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. Access denied on the backup folder
&lt;/h3&gt;

&lt;p&gt;Backup and restore run as the &lt;strong&gt;SQL Server service account&lt;/strong&gt;, not as you. A folder your login can open can still be closed to the service — network shares are the classic case — and the failure only appears when the operation actually runs. &lt;strong&gt;Fix:&lt;/strong&gt; grant the service account read/write on the backup folder, or put the file somewhere it already has access (the instance's own Backup folder always qualifies).&lt;/p&gt;

&lt;h3&gt;
  
  
  6. “The backup was taken on a newer version” — restoring down-level fails
&lt;/h3&gt;

&lt;p&gt;Backups only travel one way: a backup taken on &lt;strong&gt;SQL Server 2025&lt;/strong&gt; cannot be restored onto &lt;strong&gt;SQL Server 2022&lt;/strong&gt; or older — the restore fails on the version mismatch. Older-to-newer works (restoring a 2022 backup onto 2025 succeeds and upgrades the database's internal format as part of the restore). Plan migrations accordingly: you can move up with backup/restore, never down.&lt;/p&gt;

&lt;h3&gt;
  
  
  7. Differential or Log backup type is unavailable
&lt;/h3&gt;

&lt;p&gt;Two ordinary causes. &lt;strong&gt;No full backup exists yet&lt;/strong&gt; — differentials and log backups stand on a full backup; take one first (Part A). Or the database is under the &lt;strong&gt;SIMPLE&lt;/strong&gt; recovery model, where log backups do not exist at all. Check the model with the Step D query; if the work needs log backups, the database needs FULL (and a log-backup routine to go with it).&lt;/p&gt;

&lt;h3&gt;
  
  
  8. The restore grid shows the wrong backup set
&lt;/h3&gt;

&lt;p&gt;Remember Step 5's &lt;strong&gt;NOINIT&lt;/strong&gt;: backing up to the same &lt;code&gt;.bak&lt;/code&gt; file again &lt;em&gt;appends&lt;/em&gt; a second backup set instead of replacing the file. Restore from that file later and the &lt;strong&gt;Backup sets to restore&lt;/strong&gt; grid lists &lt;em&gt;every&lt;/em&gt; set in the file — pick by the backup date and position columns, and make sure the tick is on the set you mean. Restoring last month's set over today's database is how a routine restore becomes an incident. (The devices dialog's &lt;strong&gt;Contents&lt;/strong&gt; button lists a file's sets without starting a restore.)&lt;/p&gt;

&lt;h2&gt;
  
  
  Practice exercise
&lt;/h2&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Try it yourself (10 minutes, code in the companion folder):&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Run &lt;code&gt;setup.sql&lt;/code&gt;, take the full backup with &lt;code&gt;01-backup-full.sql&lt;/code&gt;, then break the data with &lt;code&gt;02-break-it.sql&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Restore over the damage using the SSMS dialogs (Steps 9–15) — deliberately leaving &lt;strong&gt;Close existing connections&lt;/strong&gt; unticked the first time, with your damage window still open. Read the error. Then set the three Step 13 switches properly and restore clean.&lt;/li&gt;
&lt;li&gt;Run &lt;code&gt;05-verify.sql&lt;/code&gt; and confirm the proof properly: three rows, &lt;em&gt;and&lt;/em&gt; Jonas in Berlin.&lt;/li&gt;
&lt;li&gt;Bonus: restore the same file as &lt;code&gt;DemoDbPractice&lt;/code&gt; with &lt;code&gt;04-restore-as-copy.sql&lt;/code&gt; — remember to rename the Restore As paths (or the WITH MOVE targets) first.&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;

&lt;p&gt;Reply with your backup file's size in KB — I read every one.&lt;/p&gt;

&lt;h2&gt;
  
  
  FAQ
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Do I need a full backup before a differential or log backup?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Yes. A differential captures changes &lt;em&gt;since the last full backup&lt;/em&gt;, and a log chain starts from one too. No full backup, nothing for the others to stand on — which is why Part A comes first.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Can I restore a SQL Server 2025 backup onto SQL Server 2022?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;No — restores only move to the same or a newer version (Errors #6). Going down a version means scripting the schema and moving the data, not backup/restore.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Does restoring a database overwrite it without asking?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;No. Without &lt;strong&gt;Overwrite (WITH REPLACE)&lt;/strong&gt;, SQL Server's safety checks stop a restore that would replace an existing database (Errors #1). REPLACE is a deliberate act — the dialog makes you tick it, and T-SQL makes you type it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Is a verified backup (RESTORE VERIFYONLY) a proven backup?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It proves the backup set is complete and readable — worth doing, and &lt;code&gt;01-backup-full.sql&lt;/code&gt; includes it. It does not prove the restore itself will succeed on your target, with your paths and your permissions. The only full proof is a test restore — Part D is exactly that, pointed at a copy.&lt;/p&gt;

&lt;h2&gt;
  
  
  Get the code
&lt;/h2&gt;

&lt;p&gt;The companion folder has every script from this post, in run order: &lt;code&gt;setup.sql&lt;/code&gt;, the backup statement SSMS generated (&lt;code&gt;01-backup-full.sql&lt;/code&gt;), the deliberate damage (&lt;code&gt;02-break-it.sql&lt;/code&gt;), both restores as T-SQL (&lt;code&gt;03-restore-overwrite.sql&lt;/code&gt;, &lt;code&gt;04-restore-as-copy.sql&lt;/code&gt;), and the restore-proof SELECTs (&lt;code&gt;05-verify.sql&lt;/code&gt;):&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href="https://github.com/sajjad037/visual-studio-learn-code/tree/main/topic-08-backup-restore-ssms" rel="noopener noreferrer"&gt;https://github.com/sajjad037/visual-studio-learn-code/tree/main/topic-08-backup-restore-ssms&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Sources — the official Microsoft Learn pages behind this post
&lt;/h2&gt;

&lt;p&gt;Every procedure and error above traces to Microsoft Learn (accessed November 4–5, 2026):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Back up and restore of SQL Server databases: &lt;a href="https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/back-up-and-restore-of-sql-server-databases" rel="noopener noreferrer"&gt;https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/back-up-and-restore-of-sql-server-databases&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Create a full database backup: &lt;a href="https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/create-a-full-database-backup-sql-server" rel="noopener noreferrer"&gt;https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/create-a-full-database-backup-sql-server&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Restore a database backup using SSMS: &lt;a href="https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/restore-a-database-backup-using-ssms" rel="noopener noreferrer"&gt;https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/restore-a-database-backup-using-ssms&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;SSMS 22 release notes (22.11.3): &lt;a href="https://learn.microsoft.com/en-us/ssms/release-notes-22" rel="noopener noreferrer"&gt;https://learn.microsoft.com/en-us/ssms/release-notes-22&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Editions and supported features of SQL Server 2025: &lt;a href="https://learn.microsoft.com/en-us/sql/sql-server/editions-and-components-of-sql-server-2025?view=sql-server-ver17" rel="noopener noreferrer"&gt;https://learn.microsoft.com/en-us/sql/sql-server/editions-and-components-of-sql-server-2025?view=sql-server-ver17&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;What's new in SQL Server 2025: &lt;a href="https://learn.microsoft.com/en-us/sql/sql-server/what-s-new-in-sql-server-2025?view=sql-server-ver17" rel="noopener noreferrer"&gt;https://learn.microsoft.com/en-us/sql/sql-server/what-s-new-in-sql-server-2025?view=sql-server-ver17&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Disclosure: Visual Studio Learn is reader-supported. Some links may be affiliate links, which means the channel may earn a small commission at no extra cost to you. Only tools actually used in the tutorials are ever linked, and affiliate relationships never change a verdict.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>sqlserver</category>
      <category>ssms</category>
      <category>database</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>How Do I Connect SQL Server to Visual Studio? Three Ways — Server Explorer, Object Explorer &amp; Connected Services (2026)</title>
      <dc:creator>Visual Studio Learn</dc:creator>
      <pubDate>Wed, 04 Nov 2026 09:36:44 +0000</pubDate>
      <link>https://dev.to/visualstudiolearn/how-do-i-connect-sql-server-to-visual-studio-three-ways-server-explorer-object-explorer--4m49</link>
      <guid>https://dev.to/visualstudiolearn/how-do-i-connect-sql-server-to-visual-studio-three-ways-server-explorer-object-explorer--4m49</guid>
      <description>&lt;p&gt;You connect Visual Studio to SQL Server three ways — &lt;strong&gt;Server Explorer&lt;/strong&gt; for a design-time connection, &lt;strong&gt;SQL Server Object Explorer&lt;/strong&gt; to browse and query the way you would in SSMS, and &lt;strong&gt;Connected Services&lt;/strong&gt; to wire the database into a project so your code can use it. All three are below, click by click, on Visual Studio 2022 17.14.44 with SQL Server 2025 — including the one encryption error that stops almost everyone the first time.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Versions used in this tutorial&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Visual Studio 2022 — &lt;strong&gt;17.14.44&lt;/strong&gt; (released October 29, 2026)&lt;/li&gt;
&lt;li&gt;SQL Server &lt;strong&gt;2025 (17.x)&lt;/strong&gt; — Enterprise Developer edition (free for development and testing)&lt;/li&gt;
&lt;li&gt;SQL Server Management Studio &lt;strong&gt;22.11.3&lt;/strong&gt; (for the comparison section)&lt;/li&gt;
&lt;li&gt;Microsoft.Data.SqlClient &lt;strong&gt;6.1.7&lt;/strong&gt; (the LTS line, supported until August 14, 2028)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;On Visual Studio 2026? Same three tools, same clicks — this walkthrough is captured on 2022, which is still fully supported, and everything below works identically in the newer IDE.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Before you start: set up your environment from zero
&lt;/h2&gt;

&lt;p&gt;Nothing here assumes you already have anything installed. We install Visual Studio with the right workloads, a real SQL Server you control, and SSMS — then verify all of them before connecting anything.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 1 — Visual Studio 2022 with the data workloads
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;Download &lt;strong&gt;Visual Studio 2022 Community&lt;/strong&gt; (free) from Microsoft and run the Visual Studio Installer.&lt;/li&gt;
&lt;li&gt;On the &lt;strong&gt;Workloads&lt;/strong&gt; tab, tick:

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Data storage and processing&lt;/strong&gt; — brings SQL Server Data Tools (SSDT) and SQL Server Express LocalDB. Without it, two of the three methods below do not exist in your IDE.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;.NET desktop development&lt;/strong&gt; — for the demo project in Method 3.&lt;/li&gt;
&lt;li&gt;Optional: &lt;strong&gt;Azure development&lt;/strong&gt;, only for the Azure SQL path in Method 3.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Click &lt;strong&gt;Install&lt;/strong&gt;, launch Visual Studio, and verify: &lt;strong&gt;View → SQL Server Object Explorer&lt;/strong&gt; exists. (Minimums: 64-bit Windows 11, 4 GB RAM — 16 GB recommended — and 20–50 GB free disk for a typical install.)&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Step 2 — SQL Server 2025 Developer edition
&lt;/h3&gt;

&lt;p&gt;LocalDB (from Step 1) covers Methods 1 and 3, but Method 2 deserves a real server. New in SQL Server 2025, there are &lt;strong&gt;two&lt;/strong&gt; free Developer editions: &lt;strong&gt;Enterprise Developer&lt;/strong&gt; (every Enterprise feature) and &lt;strong&gt;Standard Developer&lt;/strong&gt; (every Standard feature). Pick Enterprise Developer for a general dev machine; pick Standard Developer when production runs Standard, so no Enterprise-only feature sneaks into your schema. Both are free — no key, no subscription — licensed for development and testing, not production.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;On Microsoft's SQL Server downloads page, choose &lt;strong&gt;Developer → Enterprise Developer&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Run setup → &lt;strong&gt;Installation → New SQL Server standalone installation&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;At &lt;strong&gt;Instance Configuration&lt;/strong&gt;, keep the default instance or name yours — write the name down; you will type it into connection dialogs exactly.&lt;/li&gt;
&lt;li&gt;At &lt;strong&gt;Server Configuration&lt;/strong&gt;, set the &lt;strong&gt;SQL Server Database Engine&lt;/strong&gt; service to start &lt;strong&gt;automatically&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;At &lt;strong&gt;Database Engine Configuration → Authentication Mode&lt;/strong&gt;, choose deliberately: &lt;strong&gt;Windows authentication mode&lt;/strong&gt; is enough for this whole post and is the safer default; &lt;strong&gt;Mixed Mode&lt;/strong&gt; additionally enables SQL logins such as &lt;code&gt;sa&lt;/code&gt; — pick it only if you actually need them. You are choosing your server's security shape, not ticking a box.&lt;/li&gt;
&lt;li&gt;Click &lt;strong&gt;Add Current User&lt;/strong&gt; so your Windows account is a SQL Server administrator, then &lt;strong&gt;Install&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Verify in &lt;strong&gt;Services&lt;/strong&gt;: your instance is &lt;strong&gt;Running&lt;/strong&gt;. (Needs Windows 10 or later, 4 GB RAM recommended, 6 GB free disk.)&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Step 3 — SSMS 22 (for the comparison later)
&lt;/h3&gt;

&lt;p&gt;Download &lt;strong&gt;SQL Server Management Studio 22&lt;/strong&gt; (latest: 22.11.3) from Microsoft — a separate free tool, installed through the Visual Studio Installer — and connect it to the same instance. We will put it side by side with Visual Studio near the end.&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 4 — Verify everything
&lt;/h3&gt;

&lt;p&gt;In a terminal, run &lt;code&gt;sqllocaldb info&lt;/code&gt;. You should see &lt;strong&gt;MSSQLLocalDB&lt;/strong&gt; — the automatic LocalDB instance, owned by your Windows user, starting on demand. LocalDB is a lightweight developer edition of SQL Server Express: user mode, no service to manage, Windows-only. The Developer instance is verified in Services above. Two green checks — now the three methods.&lt;/p&gt;

&lt;h2&gt;
  
  
  Method 1 — Server Explorer: the design-time connection
&lt;/h2&gt;

&lt;p&gt;The oldest way in, and still the fastest way to attach a database to a project for design-time work.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Open &lt;strong&gt;View → Server Explorer&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Click &lt;strong&gt;Connect to Database&lt;/strong&gt; in the toolbar (or right-click &lt;strong&gt;Data Connections → Add Connection&lt;/strong&gt;).&lt;/li&gt;
&lt;li&gt;In &lt;strong&gt;Choose Data Source&lt;/strong&gt;, select &lt;strong&gt;Microsoft SQL Server&lt;/strong&gt; → OK. (Different source preselected? Use &lt;strong&gt;Change&lt;/strong&gt;.)&lt;/li&gt;
&lt;li&gt;In &lt;strong&gt;Add Connection&lt;/strong&gt;: &lt;strong&gt;Server name&lt;/strong&gt; &lt;code&gt;(localdb)\MSSQLLocalDB&lt;/code&gt;; &lt;strong&gt;Authentication:&lt;/strong&gt; Windows Authentication; &lt;strong&gt;database:&lt;/strong&gt; pick one from the drop-down.&lt;/li&gt;
&lt;li&gt;Click &lt;strong&gt;Test Connection&lt;/strong&gt;. The success message is the fastest honest check that your server name and login are both right.&lt;/li&gt;
&lt;li&gt;Click &lt;strong&gt;OK&lt;/strong&gt; and expand the connection under &lt;strong&gt;Data Connections&lt;/strong&gt; to browse tables.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;One thing old tutorials never showed: in designer flows, Visual Studio saves this connection's string into your project's configuration (the &lt;code&gt;connectionStrings&lt;/code&gt; section of App.config). That string — not the tree node — is what your application actually uses, which is why the decoding section below matters.&lt;/p&gt;

&lt;h2&gt;
  
  
  Method 2 — SQL Server Object Explorer: SSMS inside Visual Studio
&lt;/h2&gt;

&lt;p&gt;If Server Explorer is a connection, Object Explorer is a workplace. It requires SSDT from Step 1 and deliberately mirrors the SSMS tree.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Open &lt;strong&gt;View → SQL Server Object Explorer&lt;/strong&gt; (shortcut: &lt;strong&gt;Ctrl+\, Ctrl+S&lt;/strong&gt;).&lt;/li&gt;
&lt;li&gt;Right-click the &lt;strong&gt;SQL Server&lt;/strong&gt; node → &lt;strong&gt;Add SQL Server&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;In the &lt;strong&gt;Connect&lt;/strong&gt; dialog, enter your Developer instance's server name (machine name for a default instance, &lt;code&gt;HOST\INSTANCE&lt;/code&gt; for a named one), keep &lt;strong&gt;Windows Authentication&lt;/strong&gt;, click &lt;strong&gt;Connect&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Expand the instance → &lt;strong&gt;Databases&lt;/strong&gt; — tables, views and stored procedures in the same hierarchy SSMS shows.&lt;/li&gt;
&lt;li&gt;Right-click a database → &lt;strong&gt;New Query&lt;/strong&gt; and run real T-SQL:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;CREATE&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="n"&gt;dbo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;DemoCustomers&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;CustomerId&lt;/span&gt; &lt;span class="nb"&gt;INT&lt;/span&gt; &lt;span class="k"&gt;IDENTITY&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;PRIMARY&lt;/span&gt; &lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;FullName&lt;/span&gt; &lt;span class="n"&gt;NVARCHAR&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;NOT&lt;/span&gt; &lt;span class="k"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;City&lt;/span&gt; &lt;span class="n"&gt;NVARCHAR&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;100&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;NOT&lt;/span&gt; &lt;span class="k"&gt;NULL&lt;/span&gt;
&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="k"&gt;INSERT&lt;/span&gt; &lt;span class="k"&gt;INTO&lt;/span&gt; &lt;span class="n"&gt;dbo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;DemoCustomers&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;FullName&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;City&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;VALUES&lt;/span&gt;
&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="s1"&gt;'Amara'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="s1"&gt;'Toronto'&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="s1"&gt;'Jonas'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="s1"&gt;'Berlin'&lt;/span&gt;&lt;span class="p"&gt;),&lt;/span&gt;
&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="s1"&gt;'Priya'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;N&lt;/span&gt;&lt;span class="s1"&gt;'Lagos'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="n"&gt;CustomerId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;FullName&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;City&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;dbo&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;DemoCustomers&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;(The companion code folder at the end contains this exact script as &lt;code&gt;setup.sql&lt;/code&gt;, so the post, the video and the code can never drift apart.)&lt;/p&gt;

&lt;h2&gt;
  
  
  Method 3 — Connected Services: wire the database into a project
&lt;/h2&gt;

&lt;p&gt;Methods 1 and 2 connect &lt;em&gt;you&lt;/em&gt; to the database. Connected Services connects &lt;em&gt;your project&lt;/em&gt; — package references added, connection string stored properly, dependency registered.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;In &lt;strong&gt;Solution Explorer&lt;/strong&gt;, right-click the &lt;strong&gt;Connected Services&lt;/strong&gt; node → &lt;strong&gt;Add&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Choose &lt;strong&gt;SQL Server Database&lt;/strong&gt;. The Connect to dependency page offers four targets: &lt;strong&gt;SQL Server Express LocalDB&lt;/strong&gt;, &lt;strong&gt;SQL Server Database in a local container&lt;/strong&gt;, &lt;strong&gt;SQL Server Database (on-premises, local network)&lt;/strong&gt;, and &lt;strong&gt;Azure SQL Database&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Pick &lt;strong&gt;SQL Server Express LocalDB&lt;/strong&gt; → the &lt;strong&gt;MSSQLLocalDB&lt;/strong&gt; instance.&lt;/li&gt;
&lt;li&gt;For connection-string storage, choose the &lt;strong&gt;local secrets file&lt;/strong&gt; — never a source file (the decoding section explains why).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Next → Finish.&lt;/strong&gt; When the wizard completes, it stores the string in the local secrets file from Step 4 and the dependency appears under &lt;strong&gt;Service Dependencies&lt;/strong&gt;. One honest warning from this tutorial's own capture session: on our machine the wizard stopped at that last step — &lt;strong&gt;"Failed to configure Secrets store"&lt;/strong&gt; — twice, and no dependency appeared (see &lt;strong&gt;Errors you may hit #7&lt;/strong&gt;). The connection string itself was never the problem: the companion console app prints the server version and the demo rows with the same string, and Methods 1 and 2 connect with it too. If the wizard stops on your machine, store the string yourself (Error #7 shows how) and carry on.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The same dialog reaches on-premises servers and Azure SQL Database (that path needs the Azure development workload and an Azure account, and since VS 2022 17.12 it uses Microsoft Entra authentication — Visual Studio does &lt;strong&gt;not&lt;/strong&gt; create the Entra admin user on the database for you, so if none exists, sign-in fails there, not in VS).&lt;/p&gt;

&lt;h2&gt;
  
  
  Visual Studio or SSMS — which do I open?
&lt;/h2&gt;

&lt;p&gt;Not rivals: Microsoft ships both, on separate cadences, for different jobs.&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;The job&lt;/th&gt;
&lt;th&gt;Open&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Building the app that uses the database&lt;/td&gt;
&lt;td&gt;Visual Studio&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Browsing and querying while you code&lt;/td&gt;
&lt;td&gt;SQL Server Object Explorer&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Wiring a database into a project&lt;/td&gt;
&lt;td&gt;Connected Services&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Administering the server itself — backups, jobs, logins, configuration&lt;/td&gt;
&lt;td&gt;SSMS&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;SSMS administers the &lt;em&gt;server&lt;/em&gt;, whether or not any application exists; Visual Studio's tools live next to your code and its connections become part of your project. You will end up using both — that is the intended workflow. (Thursday's post goes deeper on the SSMS side: backing up and restoring this same database.)&lt;/p&gt;

&lt;h2&gt;
  
  
  Your connection string, decoded
&lt;/h2&gt;

&lt;p&gt;Everything above eventually produces one line of text. The LocalDB version, keyword by keyword:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight conf"&gt;&lt;code&gt;&lt;span class="n"&gt;Server&lt;/span&gt;=(&lt;span class="n"&gt;localdb&lt;/span&gt;)\&lt;span class="n"&gt;MSSQLLocalDB&lt;/span&gt;;&lt;span class="n"&gt;Database&lt;/span&gt;=&lt;span class="n"&gt;DemoDb&lt;/span&gt;;&lt;span class="n"&gt;Integrated&lt;/span&gt; &lt;span class="n"&gt;Security&lt;/span&gt;=&lt;span class="n"&gt;true&lt;/span&gt;;&lt;span class="n"&gt;Encrypt&lt;/span&gt;=&lt;span class="n"&gt;true&lt;/span&gt;;&lt;span class="n"&gt;TrustServerCertificate&lt;/span&gt;=&lt;span class="n"&gt;true&lt;/span&gt;;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Server&lt;/strong&gt; (Data Source) — &lt;code&gt;(localdb)\MSSQLLocalDB&lt;/code&gt; for LocalDB; &lt;code&gt;HOSTNAME&lt;/code&gt; for a default instance; &lt;code&gt;HOSTNAME\INSTANCE&lt;/code&gt; for a named one (the shape for a hosted or on-premises server too); &lt;code&gt;HOSTNAME,1433&lt;/code&gt; pins the TCP port.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Database&lt;/strong&gt; (Initial Catalog) — the database you land in.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Integrated Security=true&lt;/strong&gt; — Windows Authentication: no password in the string, and the recommended pattern for development. SQL Authentication uses &lt;strong&gt;User Id&lt;/strong&gt; + &lt;strong&gt;Password&lt;/strong&gt; instead — and then the string &lt;em&gt;is&lt;/em&gt; a secret: user secrets or an environment variable, never source control.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Encrypt=true&lt;/strong&gt; — on by default in modern tooling (error #1 below). Non-negotiable on any network you do not own.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;TrustServerCertificate=true&lt;/strong&gt; — Encrypt's local-dev companion: accept the dev instance's self-signed certificate. Correct at your desk; in production the real fix is a properly trusted certificate, not this switch.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Coming from Python/FastAPI?&lt;/strong&gt; Same anatomy, ODBC spelling — pyodbc with Microsoft ODBC Driver 18 for SQL Server:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DRIVER={ODBC Driver 18 for SQL Server};SERVER=(localdb)\MSSQLLocalDB;DATABASE=DemoDb;Trusted_Connection=yes;Encrypt=yes;TrustServerCertificate=yes
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you deployed the FastAPI app from an earlier tutorial in this series to Azure App Service, this string is exactly what its configuration needs next.&lt;/p&gt;

&lt;h2&gt;
  
  
  Errors you may hit
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. "The certificate chain was issued by an authority that is not trusted"
&lt;/h3&gt;

&lt;p&gt;The error that defines connecting to SQL Server in 2026. Since Visual Studio 17.8 the data tools enable &lt;strong&gt;Encrypt by default&lt;/strong&gt; — modern Microsoft.Data.SqlClient does the same — so your connection demands a TLS certificate from a trusted authority. A local dev instance presents a self-signed one, and the connection dies. It is not your server name, not your password, not a broken install.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;At your desk:&lt;/strong&gt; add &lt;code&gt;TrustServerCertificate=true&lt;/code&gt; (or tick the equivalent in the Connect dialog) and reconnect. Microsoft's own LocalDB examples use exactly this pair.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;In production:&lt;/strong&gt; install a certificate from a trusted authority. The trust-anything switch is a development tool, full stop.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  2. "A network-related or instance-specific error occurred…" (error 40)
&lt;/h3&gt;

&lt;p&gt;Server not found or unreachable. Causes, in order: the instance name is misspelled (the &lt;code&gt;\INSTANCE&lt;/code&gt; half especially), or the Database Engine service is stopped. Open &lt;strong&gt;Services&lt;/strong&gt;, confirm the instance is running, re-check the spelling against Step 2.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. "Login failed for user" (error 18456)
&lt;/h3&gt;

&lt;p&gt;Authentication reached the server and was refused — classically, a SQL login (&lt;code&gt;sa&lt;/code&gt;, or one you created) against a server installed in &lt;strong&gt;Windows authentication mode only&lt;/strong&gt;: Mixed Mode was never enabled at setup, or the login does not exist. Fix the Step 2 choice, or create the login under SSMS → Security.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. "(localdb) … server was not found"
&lt;/h3&gt;

&lt;p&gt;LocalDB itself is missing. The &lt;strong&gt;Data storage and processing&lt;/strong&gt; workload (or the SQL Server Express LocalDB individual component) installs it — a NuGet package does not. Visual Studio Installer → Modify → add it, then confirm with &lt;code&gt;sqllocaldb info&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. A named instance is unreachable from another machine
&lt;/h3&gt;

&lt;p&gt;Three suspects: &lt;strong&gt;TCP/IP disabled&lt;/strong&gt; in SQL Server Configuration Manager, the &lt;strong&gt;SQL Browser&lt;/strong&gt; service stopped, or the &lt;strong&gt;firewall&lt;/strong&gt; closed on port 1433. Enable, start, open, restart the instance, retest.&lt;/p&gt;

&lt;h3&gt;
  
  
  6. Python: "Data source name not found and no default driver specified"
&lt;/h3&gt;

&lt;p&gt;pyodbc cannot find the driver your string names. Install &lt;strong&gt;Microsoft ODBC Driver 18 for SQL Server&lt;/strong&gt;, then copy its name into &lt;code&gt;DRIVER={...}&lt;/code&gt; character for character — the braces and exact spacing are part of the name.&lt;/p&gt;

&lt;h3&gt;
  
  
  7. Connected Services: "Failed to configure Secrets store"
&lt;/h3&gt;

&lt;p&gt;Method 3's wizard can fail at its last step: the progress dialog ends with &lt;strong&gt;"Failed to configure Secrets store"&lt;/strong&gt; and "Failed to configure dependency SQL Server Database", and no dependency appears under &lt;strong&gt;Service Dependencies&lt;/strong&gt;. This is not hypothetical — it happened on this tutorial's own capture machine (Visual Studio Community 2022 17.14.44, November 3, 2026), twice in a row, and it persisted after running &lt;code&gt;dotnet user-secrets init&lt;/code&gt; in the project and restarting Visual Studio, the two fixes most often suggested for it.&lt;/p&gt;

&lt;p&gt;The important part: &lt;strong&gt;the failure is in the wizard's secrets-store step, not in your connection.&lt;/strong&gt; The connection string itself is unaffected — the exact same string connects fine through Server Explorer (Method 1), SQL Server Object Explorer (Method 2), and the companion console app, which is how this tutorial's demo was verified end to end. If you hit it:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Do not debug your server, your login or your string — test the same string in Method 1 first; if it connects there, the database side is proven.&lt;/li&gt;
&lt;li&gt;Store the string yourself instead: add it to your user secrets (&lt;code&gt;dotnet user-secrets set "ConnectionStrings:DatabaseConnection" "..."&lt;/code&gt;) or an environment variable, and let your code read it from configuration — the pattern the "Get the code" section uses.&lt;/li&gt;
&lt;li&gt;Treat the Connected Services dependency as a convenience that may need a Visual Studio repair or update on the affected install, not as a requirement — nothing in your project depends on the wizard having succeeded.
## Practice exercise&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Try it yourself (10 minutes, code in the description):&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Run SqlConnectCheck against LocalDB — it prints your server version and three demo rows.&lt;/li&gt;
&lt;li&gt;In SQL Server Object Explorer, run a New Query against the same instance: &lt;code&gt;CREATE DATABASE PracticeDb;&lt;/code&gt; — then change ONE word in the connection string (the database name) and re-run. PracticeDb starts empty, so watch what the checker does: it creates the DemoCustomers table inside it, seeds the same three rows, prints them back, and ends with the same success line.&lt;/li&gt;
&lt;li&gt;Now break it on purpose: mistype the instance name, re-run, and read the error like a detective — which of the post's six errors is it?
Reply with the @&lt;a class="mentioned-user" href="https://dev.to/version"&gt;@version&lt;/a&gt; line your run printed — I read every one.&lt;/li&gt;
&lt;/ol&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  FAQ
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Do I need SSMS if I have Visual Studio?&lt;/strong&gt;&lt;br&gt;
No — everything here works without it. Install SSMS when the job becomes administering the server itself: backups, jobs, logins, configuration.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Is SQL Server free for this?&lt;/strong&gt;&lt;br&gt;
Yes, for development and testing: the Developer editions and LocalDB cost nothing and need no key. Developer editions are &lt;strong&gt;not&lt;/strong&gt; licensed for production — Express is the free edition that is.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Does this work on Visual Studio 2026? VS Code?&lt;/strong&gt;&lt;br&gt;
2026: yes — same three tools, same clicks. VS Code is a different editor with its own SQL extension; a different path, not covered here.&lt;/p&gt;

&lt;h2&gt;
  
  
  Get the code
&lt;/h2&gt;

&lt;p&gt;The companion folder has the C# console checker (&lt;code&gt;SqlConnectCheck&lt;/code&gt;, Microsoft.Data.SqlClient 6.1.7 LTS, connection string from an environment variable), the Python/pyodbc version, &lt;code&gt;setup.sql&lt;/code&gt; exactly as run above, and a README with the six errors in miniature:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;a href="https://github.com/sajjad037/visual-studio-learn-code/tree/main/topic-07-connect-sql-server-vs" rel="noopener noreferrer"&gt;https://github.com/sajjad037/visual-studio-learn-code/tree/main/topic-07-connect-sql-server-vs&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Sources — the official Microsoft Learn pages behind this post
&lt;/h2&gt;

&lt;p&gt;Every version pin and procedure above traces to Microsoft Learn (accessed November 3, 2026):&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Visual Studio 2022 release notes (17.14.44): &lt;a href="https://learn.microsoft.com/en-us/visualstudio/releases/2022/release-notes" rel="noopener noreferrer"&gt;https://learn.microsoft.com/en-us/visualstudio/releases/2022/release-notes&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;SSMS 22 release notes (22.11.3): &lt;a href="https://learn.microsoft.com/en-us/ssms/release-notes-22" rel="noopener noreferrer"&gt;https://learn.microsoft.com/en-us/ssms/release-notes-22&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Microsoft.Data.SqlClient support lifecycle (6.1.7 LTS, supported to August 14, 2028): &lt;a href="https://learn.microsoft.com/en-us/sql/connect/ado-net/sqlclient-driver-support-lifecycle?view=sql-server-ver16" rel="noopener noreferrer"&gt;https://learn.microsoft.com/en-us/sql/connect/ado-net/sqlclient-driver-support-lifecycle?view=sql-server-ver16&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Editions and supported features of SQL Server 2025 (the Enterprise/Standard Developer split): &lt;a href="https://learn.microsoft.com/en-us/sql/sql-server/editions-and-components-of-sql-server-2025?view=sql-server-ver17" rel="noopener noreferrer"&gt;https://learn.microsoft.com/en-us/sql/sql-server/editions-and-components-of-sql-server-2025?view=sql-server-ver17&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;SQL Server downloads (the free Developer editions): &lt;a href="https://www.microsoft.com/en-us/sql-server/sql-server-downloads" rel="noopener noreferrer"&gt;https://www.microsoft.com/en-us/sql-server/sql-server-downloads&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Hardware and software requirements for installing SQL Server 2025: &lt;a href="https://learn.microsoft.com/en-us/sql/sql-server/install/hardware-and-software-requirements-for-installing-sql-server-2025?view=sql-server-ver17" rel="noopener noreferrer"&gt;https://learn.microsoft.com/en-us/sql/sql-server/install/hardware-and-software-requirements-for-installing-sql-server-2025?view=sql-server-ver17&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;SQL Server Express LocalDB (the automatic MSSQLLocalDB instance, and Microsoft's own LocalDB connection-string example): &lt;a href="https://learn.microsoft.com/en-us/sql/connect/ado-net/sql/sqlclient-support-localdb?view=sql-server-ver17" rel="noopener noreferrer"&gt;https://learn.microsoft.com/en-us/sql/connect/ado-net/sql/sqlclient-support-localdb?view=sql-server-ver17&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Disclosure: Visual Studio Learn is reader-supported. Some links may be affiliate links, which means the channel may earn a small commission at no extra cost to you. Only tools actually used in the tutorials are ever linked, and affiliate relationships never change a verdict.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>sqlserver</category>
      <category>visualstudio</category>
      <category>dotnet</category>
      <category>database</category>
    </item>
  </channel>
</rss>
