0

T-SQL Snapshot Backups on Availability Group Secondary Replicas Continued

In a previous post I talked about how we can use T-SQL Snapshot Backups to take application consistent snapshots of secondary replica databases. This gets around having to freeze IO on the primary database and I finished the post by saying…

But there we have it, a way to take application consistent snapshots of databases without having to worry about the effects of a stun on our applications.

Hmmmm…but does stunninng/freezing/quiescing IO on a secondary really have no effect on transactions on the primary?

Let’s have a look…

Firstly, kicking off a hammerdb workload against my database…using Anthony Nocentino’s containerised setup: –
https://github.com/nocentino/hammerdb

We can see the queries running with sp_whoisactive: –

All good…queries executing as normal. Now, let’s go and suspend the IO on the secondary database: –

ALTER SERVER CONFIGURATION SET SUSPEND_FOR_SNAPSHOT_BACKUP = ON
(GROUP = (tpcc), MODE = COPY_ONLY);

And if we check the queries again: –

Ah ha. Ok, transactions are waiting on HADR_SYNC_COMMIT.

Which makes sense right? IO is frozen on the secondary, we’re not getting an acknowledgement back that transactions have been committed, so the transactions on the primary have to wait.

So my statement in my previous post wasn’t entirely correct. True yes, we don’t have to worry about the stun on the primary database but there are knock on effects of stunning IO on the primary…so we still need to factor that into consideration when taking T-SQL Snapshot Backups on a secondary node.

Or switch the availability group into asynchronous replication (joke!)

Thanks for reading!

0

T-SQL Snapshot Backups on Availability Group Secondary Replicas

One of my favourite features of SQL Server 2022 was the T-SQL Snapshot Backups. The ability to leverage the snapshot capabilities of modern storage arrays to take application consistent snapshots of our databases is a game changer for anyone dealing with very large databases and struggling to hit their RPO within their RTO.

However, application consistent snapshots require the write IO of the database to be quiesced/frozen/stunned…and (rightly so) this can make DBAs nervous.

SQL Server 2025 introduced the ability to take full and differential backups of secondary replica databases in availability groups…but what about the T-SQL Snapshot Backups? Wouldn’t it be great if we could take those on the secondary and not have to stun IO on the primary database?

Alas, if we try to take a “normal” snapshot backup of a secondary replica: –

ALTER DATABASE [tpcc] SET SUSPEND_FOR_SNAPSHOT_BACKUP = ON

We’ll get the following error: –

Msg 1468, Level 16, State 3, Line 5
The operation cannot be performed on database “tpcc” because it is involved in a database mirroring session or an availability group. Some operations are not allowed on a database that is participating in a database mirroring session or in an availability group.
Msg 5069, Level 16, State 1, Line 5
ALTER DATABASE statement failed.

OK, I guess that makes sense…

However, I had a conversation with two awesome people (Sean Gallardy and Allan Hirt) at Microsoft and it turns out that you CAN take a snapshot of a secondary replica database!

There are a couple of conditions though…database in the secondary replica has to be read only, COPY_ONLY must be specified, and we have do to it a the SERVER CONFIGURATION level.

So if we try: –

ALTER SERVER CONFIGURATION SET SUSPEND_FOR_SNAPSHOT_BACKUP = ON
(GROUP = (tpcc), MODE = COPY_ONLY);

Ah ha! IO (write IO) is frozen on the database!

Database ‘tpcc’ acquired suspend locks in session 75.
I/O is frozen on database tpcc. No user action is required. However, if I/O is not resumed promptly, you could cancel the backup.
Database ‘tpcc’ successfully suspended for snapshot backup in session 75.

We can now take a snapshot of the volumes on our storage array and then take a METADATA_ONLY backup: –

BACKUP DATABASE [tpcc] TO DISK = 'E:\SQLBackup1\tpcc.bkm' WITH METADATA_ONLY;

This releases the stun and we have our application consistent snapshot!

I/O was resumed on database tpcc. No user action is required.
Database ‘tpcc’ released suspend locks in session 76.
Database ‘tpcc’ originally suspended for snapshot backup in session 76 successfully resumed in session 76.
Processed 0 pages for database ‘tpcc’, file ‘tpcc’ on file 3.
BACKUP DATABASE successfully processed 0 pages in 0.003 seconds (0.000 MB/sec).

Of course, if anything goes wrong and we need to abort, we can run: –

ALTER SERVER CONFIGURATION SET SUSPEND_FOR_SNAPSHOT_BACKUP = OFF
(GROUP = (tpcc));

Which will resume IO!

I/O was resumed on database tpcc. No user action is required.
Database ‘tpcc’ released suspend locks in session 76.
Database ‘tpcc’ originally suspended for snapshot backup in session 76 successfully resumed in session 76.

But there we have it, a way to take application consistent snapshots of databases without having to worry about the effects of a stun on our applications.

Thanks for reading!

0

EightKB 2026 – Schedule and Registration

Hello Hello, We. Are. Back!

The schedule for EightKB 2026 Edition has been announced!

We’re kicking off at 1pm UTC on August 20th…here’s the schedule: –

N.B. – If you click on the session on the website, it shows the session abstract…nice touch eh?

Once again we have five amazing speakers delivering five great, in-depth sessions on various SQL Server internals topics.

We only have five slots in each event which meant we ended up not picking some amazing sessions. I want to say a MASSIVE thank you to all who submitted…session selection is the WORST part of running a conference! Really, truly…thank you to everyone who submitted.

Registration is now open, it’s completely free and you can sign up here: –
https://eightkb.online/

The event will be in Zoom and we’ll have chat going in the EightKB channel in the SQL Community Slack…please come and hang out with us there!

EightKB is a 100% community driven with no sponsors so, we have our own Bonfire store selling t-shirts!

Don’t they look snazzy?!

Any money generated from the store will be put straight back into the event.

Hope to see you on August the 20th!

0

Distance Metrics for Semantic Similarity Searches in SQL Server 2025

Next up in my series talking about The Burrito Bot is diving into the different distance metrics used to calculate how a vector generated from a query compares to the vectors stored in the database.

For the Burrito Bot, this would be taking a query such as: –

“Find me a restaurant with a cozy atmosphere”

And then sending that off to a model which generates the embedding, before using either VECTOR_DISTANCE or VECTOR_SEARCH to compare that embedding (aka the returned vector) to the embeddings of review data already stored in the database.

Here’s an example using VECTOR_DISTANCE: –

DECLARE @search_text   NVARCHAR(MAX) = 'Find me a restaurant with a good atmosphere';
DECLARE @search_vector VECTOR(1536)  = AI_GENERATE_EMBEDDINGS(@search_text USE MODEL [text-embedding-3-small]);

SELECT TOP(1)
	r.[id], 
	r.[name], 
	r.[city], 
	r.[rating], 
	r.[review_count], 
	r.[address], 
	r.[phone], 
	r.[url],
	VECTOR_DISTANCE('cosine', @search_vector, e.embeddings) AS distance
FROM [data].[restaurants] r
INNER JOIN [embeddings].[restaurant_review_embeddings] e ON r.id = e.restaurant_id
ORDER BY distance;
GO

Here we are using cosine as a distance metric, but there are three available to us in SQL Server: –

  • Euclidean Distance
  • Negative Dot Product
  • Cosine Distance

In this post we’ll run through all three, see how they are calculated, and explore how they differ from each other.

Vector Magnitude

\|\mathbf{a}\| = \sqrt{\sum_{i=1}^{n} a_i^2}

But first, a word about vector magnitude. Magnitude is calculated as the square root of the sum of the vector’s squared components…and is the “length” of the vector.

However, what does that actually mean? What on earth is the length of a vector that is generated from review data?

Well, the magnitude (length) of a vector can be affected by multiple things…wording, quantity, emphasis in text, or even model behaviour.

Take these two statements…

I love burritos
vs
I really really really really love burritos

They both convey (pretty much) the same meaning…but due to wording and emphasis…could result in vectors with different magnitudes…and this is something we need to consider when choosing a distance metric when performing our calculations.

Euclidean Distance

d(\mathbf{a}, \mathbf{b}) = \sqrt{(a_1 - b_1)^2 + \dots + (a_n - b_n)^2}

This is calculated as the square root of the sum of the squared differences between each vector’s components. Bit of a mouthful, but this is the simplest metric. It’s basically the straight-line distance between two vectors in high-dimensional space.

Euclidean distance accounts for both direction and magnitude, so vectors with similar meaning but different lengths may appear far apart. This makes it useful for geometric or physical data, but often less suitable for text embeddings…so not great for the restaurant review data.

Dot Product

\mathbf{a} \cdot \mathbf{b} = \sum_{i=1}^{n} a_i b_i

Dot product is calculated as the sum of the products of each vector’s corresponding components.

SQL Server uses negative dot product, which as far as I can tell…is just the dot product multiplied by -1

Dot product measures both directional alignment and magnitude. So this metric can have the same issue as Euclidean Distance. Vectors with similar meaning could potentially be calculated as having very different scores if their magnitudes differ significantly.

Cosine Similarity

\cos(\theta) = \frac{\mathbf{a} \cdot \mathbf{b}}{\|\mathbf{a}\|\|\mathbf{b}\|}

Cosine similarity is the dot product divided by the product of the vectors’ magnitudes. It measures how closely aligned two vectors are while removing the effect of magnitude.

So what cosine similarity is really measuring is the directional similarity of the vectors. For the Burrito Bot, which is using embeddings generated from review data, this generally aligns well with semantic similarity. Basically, embeddings that point in similar directions in high-dimensional space often represent text with similar meaning.

Oh, and just a quick note…SQL Server actually uses cosine distance, not cosine similarity…as we are calculating how far the vectors are apart…not how similar they are. Cosine distance is calculated as: –

1 - \cos(\theta)

Vector Normalisation

\hat{\mathbf{a}} = \frac{\mathbf{a}}{\|\mathbf{a}\|}

Right, after all that, let’s throw a massive spanner in the works and talk about vector normalisation. This involves dividing each component in the vector by the vector’s magnitude…which scales the vector so its magnitude becomes 1.

The effect of this is that cosine similarity becomes equivalent to dot product!

And as SQL Server uses negative dot product and cosine distance, they will produce the same ordering of results for normalised vectors. Because all vectors now have the same magnitude, Euclidean Distance will also produce the same ordering of results as the other two metrics.

So if you’re working with normalised vectors…and you’re only interested in the ordering of the results rather than the actual values calculated…the choice of metric becomes much less significant.

How do we tell if the vectors are normalised? Hopefully the embedding model will tell us in its specs…but we don’t always live in a world where things are documented completely…do we? Thankfully we can use the VECTOR_NORM function within SQL to check: –

SELECT VECTOR_NORM(embeddings, 'norm2') AS length
FROM embeddings.restaurant_review_embeddings;
GO

If that returns values close to 1, then our vectors are normalised.

Hope that has been a useful dive into the different metrics available for vector distance calculations in SQL.

Thanks for reading!

0

Visualising Vectors in High Dimensional Space

Following on from my previous post on building The Burrito Bot, I want to delve into visualisation of vector embeddings that were generated from the restaurant data pulled from Google Maps.

Those embeddings had 1536 dimensions, each dimension corresponding to an axis within a high dimensional space, with embeddings that have similar meanings grouped together in that high dimensional space.

1536 dimensions…is a lot of dimensions! And for me, a hard concept to get my head around. It all just feels so abstract (to me anyway), I want to see what they actually look like!

Thankfully, there’s a website out there that can help us visualise embeddings: –
https://projector.tensorflow.org/

So let’s have a look at visualising some embeddings!

In the github repository for the Burrito bot, there are two folders under: –
https://github.com/dbafromthecold/burrito-bot/tree/main/Data/Visualise%20Data

Embeddings One contains two tsv files…this is the first set of data that I used for the bot. It contains embeddings based on the following values: –

Name
City
Rating
Reviews
Address
PhoneNumber

The embeddings.tsv is the actual embeddings generated from the model, tab delimited. The restaurant_metadata.tsv is the data (listed above) that was sent over to the model to generate the embeddings (again, tab delimited).

Click Load on the left hand side and load embeddings.tsv for Step 1 and restaurant_metadata.tsv for Step 2.

And this is what’s produced!

We can clearly see clumps of embeddings grouped together! Clicking on an embedding will show the data it contains and also the nearest embeddings to it…calculated via Cosine or Euclidean distance. Notice that the nearest “dots” on the map may not always be the ones highlighted via the distance calculations.

This is because the original embeddings exist in 1536 dimensional space, whilst what we are seeing is a 3D projection of that space. Reducing 1536 dimensions down to 3 cannot perfectly preserve every distance and relationship, so some points may appear closer or farther apart than they are in the full embedding space.

Ok, so what about the review data that I ended up using for the bot?

That’s in the second folder (Embeddings Two) …if we load that into the site, we get: –

Not so obvious grouping this time…but there are still clearly some smaller groups there and we can use the site to see the review data (click on the “dot”) to potentially work out why they are clustered together!

I found this site to be really useful in getting my head around visualising embeddings…hope it helps you too!

Thanks for reading!