Help: SQL Server

Sharing my knowlege about SQL Server Troubleshooting Skills

    Advertisements
  • Blog Stats

    • 1,300,802 hits
  • Select GETDATE()

    February 2018
    M T W T F S S
    « Jul    
     1234
    567891011
    12131415161718
    19202122232425
    262728  
  • Advertisements

Posts Tagged ‘peformance’

A-Z of In-Memory OLTP : Extended Events (XEvents)

Posted by blakhani on February 18, 2014


All of us want to know “internals” of many things. Doctors want to know internals of body; Engineer wants to know internals of machines. On the same line SQL DBA always wants to know internals of SQL Server. Sometimes there are easier ways to look at internals of SQL Server via extended events as compare to any other tool available. In this blog, we would have a look at the XEvents (eXtended Events) which are available to provide information about In-Memory OLTP. If you want to learn about XEvents, then start from Jonathan’s blog series (An XEvent a Day)

To get the list of XEvents which are related to In-Memory OLTP, we can either use query or Interface. There are three packages available for XTP (Hope you have read my initial blog of series which explains XTP, if not, read here)

Name Description
XtpRuntime Extended events for the XTP Runtime
XtpCompile Extended events for the XTP Compile
XtpEngine Extended events for the XTP Engine

 

We can view events for Registered Packages using below queries. I have modified the one available on books online. Here is the query and the output

USE msdb 

SELECT p.name, 
       c.event, 
       k.keyword, 
       c.channel, 
       c.description 
FROM   (SELECT event_package=o.package_guid, 
               o.description, 
               event=c.object_name, 
               channel=v.map_value 
        FROM   sys.dm_xe_objects o 
               LEFT JOIN sys.dm_xe_object_columns c 
                      ON o.name = c.object_name 
               INNER JOIN sys.dm_xe_map_values v 
                       ON c.type_name = v.name 
                          AND c.column_value = Cast(v.map_key AS NVARCHAR) 
        WHERE  object_type = 'event' 
               AND ( c.name = 'CHANNEL' 
                      OR c.name IS NULL )) c 
       LEFT JOIN (SELECT event_package=c.object_package_guid, 
                         event=c.object_name, 
                         keyword=v.map_value 
                  FROM   sys.dm_xe_object_columns c 
                         INNER JOIN sys.dm_xe_map_values v 
                                 ON c.type_name = v.name 
                                    AND c.column_value = v.map_key 
                                    AND 
                         c.type_package_guid = v.object_package_guid 
                         INNER JOIN sys.dm_xe_objects o 
                                 ON o.name = c.object_name 
                                    AND o.package_guid = c.object_package_guid 
                  WHERE  object_type = 'event' 
                         AND c.name = 'KEYWORD') k 
              ON k.event_package = c.event_package 
                 AND ( k.event = c.event 
                        OR k.event IS NULL ) 
       INNER JOIN sys.dm_xe_packages p 
               ON p.guid = c.event_package 
WHERE  name LIKE '%xtp%' 
        OR c.event LIKE '%xtp%' 
        OR c.description LIKE '%xtp%' 
        OR k.event LIKE '%xtp%' 
        OR k.keyword LIKE '%xtp%' 
ORDER  BY 1, 
          keyword DESC, 
          channel, 
          event  

Here is the output

Name Event keyword channel description
sqlserver natively_compiled_proc_slow_parameter_passing xtp Analytic Occurs when a Hekaton procedure call dispatch goes to slow parameter passing code path
sqlserver after_natively_compiled_proc_entry_removal_on_drop xtp Debug Fired after the procedure cache entry is flushed when dropping a natively compiled procedure.
sqlserver before_natively_compiled_proc_entry_removal_on_drop xtp Debug Fired before the procedure cache entry is flushed when dropping a natively compiled procedure.
sqlserver natively_compiled_proc_execution_started xtp Debug Fired before a natively compiled procedure is executed.
sqlserver xtp_create_procedure xtp Debug Occurs at start of XTP procedure creation.
sqlserver xtp_create_table xtp Debug Occurs at start of XTP table creation.
sqlserver xtp_deploy_done xtp Debug Occurs at completion of XTP object deployment.
sqlserver xtp_matgen xtp Debug Occurs at start of MAT generation.
sqlserver xtp_offline_checkpoint_scan_start xtp Debug Fired by XTP offline checkpoint when the checkpoint thread begins.
sqlserver xtp_offline_checkpoint_scan_stop xtp Debug Fired by XTP offline checkpoint when the checkpoint thread stops.
sqlserver xtp_recover_done xtp Debug Occurs at completion of log recovery of XTP table.
sqlserver xtp_recover_table xtp Debug Occurs at start of log recovery of XTP table.
sqlserver xtp_storage_table_create xtp Debug Occurs at just before the XTP storage table is created.
XtpCompile cgen deploy Debug Occurs at start of C code generation.
XtpCompile invoke_cl deploy Debug Occurs prior to the invocation of the C compiler.
XtpCompile mat_export deploy Debug Occurs at start of MAT export.
XtpCompile pit_export deploy Debug Occurs at start of PIT export.
XtpCompile pitgen_procs deploy Debug Occurs at start of PIT generation for procedures.
XtpCompile pitgen_tables deploy Debug Occurs at start of PIT generation for tables.
XtpEngine after_changestatetx_event transaction Debug Fires after transaction changes state
XtpEngine alloctx_event transaction Debug  
XtpEngine attempt_committx_event transaction Debug Is raised when a transaction is asked to commit
XtpEngine before_changestatetx_event transaction Debug Fires before transaction changes state
XtpEngine dependency_acquiredtx_event transaction Debug Raised after transaction takes a dependency on another transaction
XtpEngine endts_acquiredtx_event transaction Debug Fires after transaction acquires an end timestamp
XtpEngine redo_single_hk_record transaction Debug Redo on a HK log record
XtpEngine waiting_for_dependenciestx_event transaction Debug Raised when we have explicitly waited for dependencies to clear
XtpEngine xtp_create_log_record transaction Debug Fires when the XTP engine creates a log record.
XtpEngine gc_base_generation_evaluation gc Debug Indicates that an evaluation of updating the GC base generation has been made.
XtpEngine gc_base_generation_updated gc Debug Indicates that the oldest active transaction hint used for calculating the GC base generation has been updated.
XtpEngine gc_cycle_completed gc Debug Indicates that a GC notification has been enqueued.
XtpEngine gc_notification gc Debug Indicates that a GC notification has not being able to process a notification.
XtpEngine xtp_checkpoint_file_flush checkpoint Debug Indicates the point at which a given file has been flushed to disk.
XtpEngine xtp_checkpoint_file_flush_complete checkpoint Debug Indicates the point at which all in-flight buffers have been flushed to disk.
XtpEngine xtp_checkpoint_file_read checkpoint Debug Indicates reading of a file in XTP checkpoint recovery.
XtpEngine xtp_checkpoint_write_io checkpoint Debug Indicates that the checkpointing subsystem has issued or completed a write IO.
XtpEngine xtp_root_deserialized checkpoint Debug Indicates that the load of a checkpoint root is complete.
XtpEngine xtp_root_serialized checkpoint Debug Indicates that the write of the checkpoint root is complete.
XtpRuntime bind_md deploy Debug Occurs prior to binding metadata for a memory optimized table.
XtpRuntime bind_tables deploy Debug Occurs prior to binding tables for a natively compiled procedure.
XtpRuntime create_table deploy Debug Occurs prior to creating memory optimized table.
XtpRuntime deserialize_md deploy Debug Occurs prior to deserializing metadata.
XtpRuntime load_dll deploy Debug Occurs prior to loading the generated DLL.
XtpRuntime recover_done deploy Debug Occurs at completion of checkpoint recovery of a memory optimized table.
XtpRuntime recover_table deploy Debug Occurs at start of checkpoint recovery of a memory optimized table.
XtpRuntime serialize_md deploy Debug Occurs prior to serializing metadata.

 

This output shows something interesting. Notice that most of the events are under “Debug” Channel. This means, if we would go to wizard of creation of XEvent session in SSMS, we would not see them because Debug channel is not checked by default.

image

After checking Debug, we should be able to see the events. In below, I have put filter of work XTP.

image

Let’s use XEvent to understand a concept. We have learned that DLLs of table is loaded as soon as database is started whereas the stored procedure DLL is loaded when its first executed. We have already discussed this concepts in Behind the Scenes

To demonstrate, I have created below XEvent Session. My database already has table and natively compiled stored procedure.

 CREATE EVENT SESSION [SQLServerHelp] ON SERVER 

     ADD EVENT sqlserver.database_started 
        (ACTION(sqlos.cpu_id, sqlserver.database_id) 
            WHERE ([database_id] = (5)))
    ,ADD EVENT XtpRuntime.load_dll 
        (ACTION(sqlos.cpu_id, sqlserver.client_hostname)) 
        
    ADD TARGET package0.event_file (SET filename = N'SQLServerHelp')
    
    WITH (
            MAX_MEMORY = 4096 KB
            ,EVENT_RETENTION_MODE = ALLOW_SINGLE_EVENT_LOSS
            ,MAX_DISPATCH_LATENCY = 30 SECONDS
            ,MAX_EVENT_SIZE = 0 KB
            ,MEMORY_PARTITION_MODE = NONE
            ,TRACK_CAUSALITY = OFF
            ,STARTUP_STATE = ON
            )
GO

 

I have put filter on database_id = 5 which you may want to change based on your system. After creating the session, I restarted SQL Server and after some time I executed stored procedure as well. As we can see in below that table DLL is loaded before database startup was complete.

image

Also notice that stored procedure DLL was loaded when I have manually executed stored procedure. Wow! extended events have confirmed our learning about DLLs generation and loading.

Conclusion

There are various extended events which can help us understand internals of hekaton / In-Memory OLTP. We will try to use more and see practical of theory which we have learned so far in this A-Z Series.

Hope you have learned something new today!

  • Cheers,
  • Balmukund Lakhani
  • Twitter @blakhani
  • Author: SQL Server 2012 AlwaysOnPaperback, Kindle
  • Advertisements

    Posted in A - Z Series, In Memory OLTP, In-Memory OLTP, SQL Server 2014 | Tagged: , , , , , , , , , , , , , , , | Leave a Comment »

    A-Z of In-Memory OLTP : Performance Monitor Counters

    Posted by blakhani on February 13, 2014


    Have you ever had a chance to see how athletes train? The coach is constantly watching the stopwatch while the athletes make multiple runs. The stopwatch is used to check the performance of students as they perform the run. In a similar way, SQL Server In-Memory OLTP performance can be monitored using Performance Monitor (PerfMon). In this blog we will discuss about some of the performance counters we can use to monitor various parameters of In-Memory OLTP.

    We must call out a difference between the way In-Memory OLTP counters (also known as XTP) vs. traditional counters are laid out in perfmon. If we look at earlier performance counters, the object is Instance specific and under that we have counter (Refer Image#1)

    image
    Image#1 Layout of Traditional SQL Counters

    On the other hand, for XTP the counter objects are listed first and under that we have instance names listed. (Refer Image#2)

    image
    Image#2 Layout of XTP related SQL Counters

    On my machine I only have one default instance and that’s why we see only MSSQLSERVER under “Instance of selected object”. In CTP2, we can see below performance monitor objects.

    XTP Cursors
    XTP Garbage Collection
    XTP Phantom Processor
    XTP Transaction Log
    XTP Transactions

    The list of various counters can be achieved using below SQL Server query.

    SELECT * 
    FROM sys.dm_os_performance_counters 
    WHERE object_name LIKE '%xtp%'
    

    image
    Image#3 SQL query to get list of XTP related SQL Counters

    The meaning of various counters is available on books online.

    To demonstrate one of the theory which we learned earlier, we would use “XTP Transaction Log” counter for demo. In this blog about transaction logging concepts, we read “Transaction log records are written only if the transaction on in-memory table is committed. This would mean that no UNDO information would be logged“.

    Here is the information about counters under “XTP Transaction Log” taken from book online

    Counter

    Description

    Log bytes written/sec

    The number of bytes written to the SQL Server transaction log by the XTP engine (on average), per second.

    Log records written/sec

    The number of records written to the SQL Server transaction log by the XTP engine (on average), per second.

     

    Here is the script which we can run and capture perform at the same time.

    Select Getdate() AS 'begin of Transaction 1'
    INSERT INTO [dbo].[MyFirstMemporyOptimizedTable]
        ([iID],[vFName],[vSite])
         VALUES
        (1,'Balmukund','SQLServer-Help.com')
    Select Getdate() AS 'End of Transaction 1'
    
    BEGIN TRAN
    Select Getdate()  AS 'begin of Transaction 2'
    INSERT INTO [dbo].[MyFirstMemporyOptimizedTable]
        ([iID],[vFName],[vSite])
         VALUES
        (2,'Balmukund','SQLServer-Help.com')
    -- Wait for 10 second
    waitfor delay '00:00:10'
    COMMIT TRAN
    Select Getdate()  AS 'commit of Transaction 2'
    
    BEGIN TRAN
    Select Getdate() AS 'begin of Transaction 3'
    INSERT INTO [dbo].[MyFirstMemporyOptimizedTable]
        ([iID],[vFName],[vSite])
         VALUES
        (3,'Balmukund','SQLServer-Help.com')
    -- Wait for 10 second
    waitfor delay '00:00:10'
    ROLLBACK TRAN
    Select Getdate() AS 'rollback of Transaction 3'
    
    

    Here is the output and perfmon data.

    image

    Image#4 perfmon counter and transaction

    Here are the conclusion we can make from the graph.

    • Logging is done at commit time of transaction. We introduced 10 second delay in our script and due to that second spike appears.
    • For uncommitted/rollback of transaction nothing is logged in transaction log.  

    Stay tune for learning more on Hekaton / In-Memory OLTP.

  • Cheers,
  • Balmukund Lakhani
  • Twitter @blakhani
  • Author: SQL Server 2012 AlwaysOnPaperback, Kindle
  • Posted in A - Z Series, In Memory OLTP, In-Memory OLTP, SQL Server 2014 | Tagged: , , , , , , , , , , , , , , , | Leave a Comment »

    A-Z of In-Memory OLTP : Durable vs. Non-durable tables

    Posted by blakhani on January 28, 2014


    Can you think of a situation where you don’t want to log anything in SQL Server and you are OK even if data is lost? What comes to your mind? Staging tables used in loading phase of Data warehouses? ASP Session state? Temporary logging tables?

    If you have such situations where data is temporary and you are OK to lose the data due to SQL Server restart then you can think of non-durable tables in SQL Server in-memory OLTP. By default, tables are durable. We have briefly discussed here in earlier blog of this series. This is defined by DURABILITY parameter during created table syntax. This indicates whether we want data in the table to be persisted when database is restarted (via offline/online, SQL Service restart or SQL crash). Non durable tables would have SCHEMA_ONLY as the value passed to the durability parameter. Note that these tables are different from the temporary table which we create in tempdb (#table and ##table). One major difference is that tempdb tables are not memory optimized and they won’t be able to survive after restart, including schema.

    We have already discussed “How In-Memory Table is durable” in this blog. Since transaction logging is not done for non-durable table, the data insertion is faster (actually much.. much faster) than durable table, of course at the cost of data durability. Let’s have a look at them in action. We would created two tables with same schema, one being durable (SCHEMA_AND_DATA durability) and another being non-durable (SCHEMA_DURABILITY)

    -- Create database with IMO Filegroup, If exists drop it.
    Use Master
    go
    If db_id('SQLSeverHelp_IMO') is NOT NULL
    drop database SQLSeverHelp_IMO
    GO
    CREATE DATABASE SQLSeverHelp_IMO 
        ON PRIMARY (
        NAME = [SQLSeverHelp_IMO_data]
        ,FILENAME = 'C:\IMO_Database\SQLSeverHelp_IMO.mdf'
        )
        
        ,FILEGROUP [SQLSeverHelp_IMO_FG] CONTAINS MEMORY_OPTIMIZED_DATA ( 
        NAME = [SQLSeverHelp_IMO_dir]
        ,FILENAME = 'C:\IMO_Database\SQLSeverHelp_IMO_dir'
        ) 
        
        LOG ON (
        NAME = [SQLSeverHelp_IMO_log]
        ,Filename = 'C:\IMO_Database\SQLSeverHelp_IMO_log.ldf'
        ) 
    GO
    
    
    -- In-Memory table, Durable
    Use SQLSeverHelp_IMO
    GO
    CREATE TABLE DurableInMemoryOptimizedTable
    (
    iID INT NOT NULL PRIMARY KEY NONCLUSTERED HASH WITH (BUCKET_COUNT = 100000),
    vFName VARCHAR(20) NOT NULL,
    vLName VARCHAR(20) NOT NULL
    ) WITH (MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_AND_DATA)
    GO
    
    -- In-Memory table, non-durable
    Use SQLSeverHelp_IMO
    GO
    CREATE TABLE NonDurableInMemoryOptimizedTable
    (
    iID INT NOT NULL PRIMARY KEY NONCLUSTERED HASH WITH (BUCKET_COUNT = 100000),
    vFName VARCHAR(20) NOT NULL,
    vLName VARCHAR(20) NOT NULL
    ) WITH (MEMORY_OPTIMIZED = ON, DURABILITY = SCHEMA_ONLY)
    GO
    
    

    Since both tables are memory optimized, both would have their own DLLs generated. We have discussed DLLs for table in earlier blog here.

    image

    Let’s load same amount of data in both tables. I have randomly selected 90000 rows (multiple of three – as I have to insert three important names). First I am inserting into Durable table using below script.

    -- Inserting 90000 rows into Durable table.
    set nocount on
    go
    DECLARE @counter INT 
    SET @counter = 1
    
    WHILE @counter <= 90000 
      BEGIN 
          INSERT INTO dbo.DurableInMemoryOptimizedTable 
          VALUES      (@counter, 'SQLServer-Help.com','Balmukund Lakhani'),
                      (@counter+1, 'ExtremeExperts.com','Vinod Kumar M'),
                      (@counter+2, 'SQLAuthority.com','Pinal Dave') 
    
          SET @counter = @counter + 3
      END
    

    image

    as we can see it was around 30 seconds on my VM. and now.. non-durable table using below script.

    set nocount on
    go
    DECLARE @counter INT 
    SET @counter = 1
    
    WHILE @counter <= 90000 
      BEGIN 
          INSERT INTO dbo.NonDurableInMemoryOptimizedTable 
          VALUES      (@counter, 'SQLServer-Help.com','Balmukund Lakhani'),
                      (@counter+1, 'ExtremeExperts.com','Vinod Kumar M'),
                      (@counter+2, 'SQLAuthority.com','Pinal Dave') 
    
          SET @counter = @counter + 3
      END
    

    image

    How much time do you see in above screen shot? zero ?Trust me, it was almost instantaneous! You don’t trust me? Let count rows from both the tables.

    -- Verify data is present in both tables.
    select COUNT(*) from NonDurableInMemoryOptimizedTable
    go
    select COUNT(*) from DurableInMemoryOptimizedTable
    go
    

    image

    Still don’t trust me? Try yourself!

    Now, the test of survival! I would take database offline and bring it online. For SCHEMA_ONLY durable table, the data would be cleaned, but schema would remain. Let’s test.

    -- take database offline and bring online.
    Use Master
    go
    ALTER DATABASE SQLSeverHelp_IMO SET OFFLINE WITH ROLLBACK IMMEDIATE
    GO
    ALTER DATABASE SQLSeverHelp_IMO SET ONLINE
    GO
    -- count the rows again
    USE SQLSeverHelp_IMO
    go
    select COUNT(*) from NonDurableInMemoryOptimizedTable
    go
    select COUNT(*) from DurableInMemoryOptimizedTable
    go
    
    

    image

    As expected, rows in NonDurableInMemoryOptimizedTable couldn’t survive database restart.

    To summarize, for non durable table only schema (table definition) would be available after restart/reboot/crash. In other words, it’s a permanent table with temporary data (consistent till restart). Non-durable table are faster in data loading at the cost of data durability. They would be a perfect fit for certain requirements need but useless for others. You MUST evaluate and understand risk of non durable tables before putting them in production. 

    Hope you have learned something new.

  • Cheers,
  • Balmukund Lakhani
  • Twitter @blakhani
  • Author: SQL Server 2012 AlwaysOnPaperback, Kindle
  • Posted in A - Z Series, In Memory OLTP, In-Memory OLTP, SQL Server 2014 | Tagged: , , , , , , , , , , , , , , , , | 5 Comments »